2

我一直在尝试在我的 laravel 项目中使用 AJAX,但它总是返回错误,

NotFoundHttpException on RouteCollection.php", "line": 179

我在 web.php 中的路线是

Route::post('/ajaxRequest','AjaxController@index');

控制器代码是

class AjaxController extends Controller {
   public function index(){
      $msg = "Ajax test message";
      return response()->json(array('msg'=> $msg), 200);
   }
}

我使用的 Ajax 调用是

    $.ajax({
             type:'POST',
             url:'{{url("/ajaxRequest")}}',
             datatype:'json',
             data: pass,
             success:function(data){
                $("#result").html(data.msg);
              }
            }).fail(function (jqXHR, textStatus, error) {
                // Handle error here
                $("#result").html(jqXHR.responseText);
});

并将元标记内容用于 csrf_token

<meta name="csrf-token" content="{!! csrf_token() !!}">

并使用检索值

var pass={'_token': $('meta[name="csrf-token"]').attr('content')};

请帮我解决这个错误。

4

2 回答 2

1

改变路线到这个

Route::post('/ajaxRequest','AjaxController@index')->name('routeName');

并在 ajax 请求中进行以下更改:

 $.ajax({
             type:'POST',
             url:'/ajaxRequest',  //if in js file
             url:'{{route("routeName")}}',  //if in blade file 
             datatype:'json',
             data: pass,
             success:function(data){
                $("#result").html(data.msg);
              }
            }).fail(function (jqXHR, textStatus, error) {
                // Handle error here
                $("#result").html(jqXHR.responseText);
});
于 2018-10-08T09:29:24.893 回答
0

使用路由名称调用路由

路由文件

Route::post('/ajaxRequest','AjaxController@index')->name('ajaxRequest');

还有你的ajax请求

 $.ajax({
             type:'POST',
             url:'{{route("ajaxRequest")}}',
             datatype:'json',
             data: pass,
             success:function(data){
                $("#result").html(data.msg);
              }
            }).fail(function (jqXHR, textStatus, error) {
                // Handle error here
                $("#result").html(jqXHR.responseText);
});
于 2018-10-08T09:30:15.913 回答