我正在用Laquvel 5和Jquery ajax开发一个应用程序。我在视图中有一个选项卡面板。当点击一个标签按钮时它正在加载一个初始表单。它加载了jquery ejax而没有任何问题。之后用户可以将数据输入到表单中,当单击“更新”按钮时,数据应使用jquery ajax保存到数据库。基本上没有页面刷新。
虽然之前的ajax表单加载工作,但点击此按钮,页面刷新并显示令牌不匹配异常。我也包含了csrf令牌。无法确定原因是什么。我已将csrf令牌作为元内容包含在内像这样的价值,
<meta name="csrf-token" content="{{csrf_token()}}" />
在jquery ajax代码中,获得这样的值。
var CSRF_TOKEN=$('meta[name="csrf-token"]').attr('content');
以下是Laravel堆栈跟踪,
TokenMismatchException in compiled.php line 2440:
in compiled.php line 2440
at VerifyCsrfToken->handle(object(Request), object(Closure)) in VerifyCsrfToken.php line 17
at VerifyCsrfToken->handle(object(Request), object(Closure)) in compiled.php line 8944
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 12083
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in compiled.php line 8944
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 10785
at StartSession->handle(object(Request), object(Closure)) in compiled.php line 8944
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 11789
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in compiled.php line 8944
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 11738
at EncryptCookies->handle(object(Request), object(Closure)) in compiled.php line 8944
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in compiled.php line 2478
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in compiled.php line 8944
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in compiled.php line 8935
at Pipeline->then(object(Closure)) in compiled.php line 1891
at Kernel->sendRequestThroughRouter(object(Request)) in compiled.php line 1880
at Kernel->handle(object(Request)) in index.php line 53
答案 0 :(得分:2)
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
在文档中。
答案 1 :(得分:0)
php artisan clear-compiled
通过访问ajax请求中的{{csrf_token()}},将csrf_token包含在请求中。