Laravel 5.5 ajax 调用 419(状态未知) [英] Laravel 5.5 ajax call 419 (unknown status)
本文介绍了Laravel 5.5 ajax 调用 419(状态未知)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我进行了 ajax 调用,但不断收到此错误:
I do an ajax call but I keep getting this error:
419(未知状态)
不知道是什么原因导致我在其他帖子中看到它必须使用 csrf 令牌做一些事情但我没有表格所以我不知道如何解决这个问题.
No idea what is causing this I saw on other posts it has to do something with csrf token but I have no form so I dont know how to fix this.
我的电话:
$('.company-selector li > a').click(function(e) {
e.preventDefault();
var companyId = $(this).data("company-id");
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/fetch-company/' + companyId,
dataType : 'json',
type: 'POST',
data: {},
contentType: false,
processData: false,
success:function(response) {
console.log(response);
}
});
});
我的路线:
Route::post('fetch-company/{companyId}', 'HomeController@fetchCompany');
我的控制器方法
/**
* Fetches a company
*
* @param $companyId
*
* @return array
*/
public function fetchCompany($companyId)
{
$company = Company::where('id', $companyId)->first();
return response()->json($company);
}
最终目标是在 html 元素中显示响应中的某些内容.
The ultimate goal is to display something from the response in a html element.
推荐答案
在 head 部分使用:
Use this in the head section:
<meta name="csrf-token" content="{{ csrf_token() }}">
并在ajax中获取csrf令牌:
and get the csrf token in ajax:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
请参考 Laravel 文档 csrf_token
Please refer Laravel Documentation csrf_token
这篇关于Laravel 5.5 ajax 调用 419(状态未知)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文