laravel5.5 ajax,php - Laravel 5.5 ajax call 419(未知状态)

php - Laravel 5.5 ajax call 419(未知状态)

我做了一个ajax调用,但我一直收到这个错误:

419(未知状态)

不知道是什么导致我在其他帖子上看到它必须用csrf令牌做一些事情,但我没有形式所以我不知道如何解决这个问题。

我的电话:

$('.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元素中显示响应中的内容。

Chris asked 2019-05-11T03:36:01Z

12个解决方案

159 votes

在头部使用:

并在ajax中获取csrf标记:

$.ajaxSetup({

headers: {

'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

}

});

请参阅Laravel Documentation csrf_token

Kannan K answered 2019-05-11T03:36:28Z

15 votes

解决此问题的另一种方法是在ajax数据中使用_token字段,并在blade中设置值{{csrf_token()}}。 这是我刚刚尝试过的工作代码。

$.ajax({

type: "POST",

url: '/your_url',

data: { somefield: "Some field value", _token: '{{csrf_token()}}' },

success: function (data) {

console.log(data);

},

error: function (data, textStatus, errorThrown) {

console.log(data);

},

});

Waqas Bukhary answered 2019-05-11T03:36:54Z

8 votes

这与Kannan的答案类似。 但是,这解决了不应将令牌发送到跨域网站的问题。 如果是本地请求,则仅设置标头。

HTML:

JS:

$.ajaxSetup({

beforeSend: function(xhr, type) {

if (!type.crossDomain) {

xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));

}

},

});

Damien Ó Ceallaigh answered 2019-05-11T03:37:26Z

6 votes

在您的页面中使用它

并在您的ajax中使用它在数据中:

_token: '{!! csrf_token() !!}',

那是:

$.ajax({

url: '/fetch-company/' + companyId,

dataType : 'json',

type: 'POST',

data: {

_token: '{!! csrf_token() !!}',

},

contentType: false,

processData: false,

success:function(response) {

console.log(response);

}

});

谢谢。

Y. Joy Ch. Singha answered 2019-05-11T03:38:13Z

4 votes

在我的情况下,我忘了将csrf_token输入添加到提交的表单。所以我这样做了HTML:

...

..

JS:

//setting containers

var _token = $('input#_token').val();

var l_img = $('input#l_img').val();

var formData = new FormData();

formData.append("_token", _token);

formData.append("l_img", $('#l_img')[0].files[0]);

if(!l_img) {

//do error if no image uploaded

return false;

}

else

{

$.ajax({

type: "POST",

url: "/my_url",

contentType: false,

processData: false,

dataType: "json",

data : formData,

beforeSend: function()

{

//do before send

},

success: function(data)

{

//do success

},

error: function(jqXhr, textStatus, errorThrown) //jqXHR, textStatus, errorThrown

{

if( jqXhr.status === "422" ) {

//do error

} else {

//do error

}

}

});

}

return false; //not to post the form physically

4 votes

您的会话域可能与您的应用程序URL和/或用于访问该应用程序的主机不匹配。

1.)检查.env文件:

SESSION_DOMAIN=example.com

APP_URL=example.com

2.)检查config / session.php

验证值以确保它们是正确的。

Jeff Callahan answered 2019-05-11T03:39:31Z

2 votes

即使您有csrf_token,如果您使用Laravel Policies验证您的控制器操作,您也可以获得419响应。 在这种情况下,您应该在Policy类中添加必要的策略函数。

Tharanga answered 2019-05-11T03:39:58Z

2 votes

如果您已经完成了上述建议并仍然遇到问题。

确保env变量:

SESSION_SECURE_COOKIE

如果您没有SSL证书,则设置为false,如本地。

2Fwebd answered 2019-05-11T03:40:49Z

2 votes

如果要从文件加载.js,则必须在“main”.blade.php文件中使用csrf_token设置变量,在该文件中导入.js并在ajax调用中使用该变量。

index.blade.php

...

...

var token = '{{ csrf_token() }}';

anotherfile.js

$.ajax({

url: 'yourUrl',

type: 'POST',

data: {

'_token': token

},

dataType: "json",

beforeSend:function(){

//do stuff

},

success: function(data) {

//do stuff

},

error: function(data) {

//do stuff

},

complete: function(){

//do stuff

}

});

Wolfernand answered 2019-05-11T03:41:29Z

1 votes

一些refs =>

...

// CSRF for all ajax call

...

...

// CSRF for all ajax call

$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content') } });

...

WHY answered 2019-05-11T03:41:55Z

1 votes

只需序列化表单数据并解决您的问题。

data: $('#form_id').serialize(),

Muhammad Umair answered 2019-05-11T03:42:22Z

1 votes

你必须得到csrf令牌..

$.ajaxSetup({

headers: {

'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

}

});

在做同样的问题后上升,只需添加此元标记234422446737073152

在此之后也会出现错误,您可以检查Ajax错误。 然后还检查Ajax错误

$.ajax({

url: 'some_unknown_page.html',

success: function (response) {

$('#post').html(response.responseText);

},

error: function (jqXHR, exception) {

var msg = '';

if (jqXHR.status === 0) {

msg = 'Not connect.\n Verify Network.';

} else if (jqXHR.status == 404) {

msg = 'Requested page not found. [404]';

} else if (jqXHR.status == 500) {

msg = 'Internal Server Error [500].';

} else if (exception === 'parsererror') {

msg = 'Requested JSON parse failed.';

} else if (exception === 'timeout') {

msg = 'Time out error.';

} else if (exception === 'abort') {

msg = 'Ajax request aborted.';

} else {

msg = 'Uncaught Error.\n' + jqXHR.responseText;

}

$('#post').html(msg);

},

});

Balaji Rajendran answered 2019-05-11T03:43:02Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值