Chr*_*ris 123 php ajax jquery laravel
我做了一个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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
我的路线:
Route::post('fetch-company/{companyId}', 'HomeController@fetchCompany');
Run Code Online (Sandbox Code Playgroud)
我的控制器方法
/**
* Fetches a company
*
* @param $companyId
*
* @return array
*/
public function fetchCompany($companyId)
{
$company = Company::where('id', $companyId)->first();
return response()->json($company);
}
Run Code Online (Sandbox Code Playgroud)
最终目标是在html元素中显示响应中的内容.
Kan*_*n K 252
在头部使用:
<meta name="csrf-token" content="{{ csrf_token() }}">
Run Code Online (Sandbox Code Playgroud)
并在ajax中获取csrf标记:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Run Code Online (Sandbox Code Playgroud)
请参阅Laravel Documentation csrf_token
Waq*_*ary 24
解决此问题的另一种方法是使用_tokenajax数据中的字段并设置{{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);
},
});
Run Code Online (Sandbox Code Playgroud)
Dam*_*igh 11
这与Kannan的答案类似.但是,这解决了不应将令牌发送到跨域网站的问题.如果是本地请求,则仅设置标头.
HTML:
<meta name="csrf-token" content="{{ csrf_token() }}">
Run Code Online (Sandbox Code Playgroud)
JS:
$.ajaxSetup({
beforeSend: function(xhr, type) {
if (!type.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
},
});
Run Code Online (Sandbox Code Playgroud)
您的会话域可能与您的应用程序URL和/或用于访问该应用程序的主机不匹配.
1.)检查.env文件:
SESSION_DOMAIN=example.com
APP_URL=example.com
Run Code Online (Sandbox Code Playgroud)
2.)检查config/session.php
验证值以确保它们是正确的.
如果您已经完成了上述建议,但问题仍然存在。
确保 env 变量:
SESSION_SECURE_COOKIE
Run Code Online (Sandbox Code Playgroud)
false 如果您没有 SSL 证书,则设置为,例如在本地。
在您的页面中使用它
<meta name="csrf-token" content="{{ csrf_token() }}">
Run Code Online (Sandbox Code Playgroud)
并在您的ajax中使用它在数据中:
_token: '{!! csrf_token() !!}',
Run Code Online (Sandbox Code Playgroud)
那是:
$.ajax({
url: '/fetch-company/' + companyId,
dataType : 'json',
type: 'POST',
data: {
_token: '{!! csrf_token() !!}',
},
contentType: false,
processData: false,
success:function(response) {
console.log(response);
}
});
Run Code Online (Sandbox Code Playgroud)
谢谢.
小智 6
如果您要从文件加载 .js,则必须在导入 .js 的“主”.blade.php 文件中使用 csrf_token 设置一个变量,并在 ajax 调用中使用该变量。
索引.blade.php
...
...
<script src="{{ asset('js/anotherfile.js') }}"></script>
<script type="text/javascript">
var token = '{{ csrf_token() }}';
</script>
Run Code Online (Sandbox Code Playgroud)
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
}
});
Run Code Online (Sandbox Code Playgroud)
就我而言,我忘记将 csrf_token 输入添加到提交的表单中。所以我做了这个 HTML:
<form class="form-material" id="myform">
...
<input type="file" name="l_img" id="l_img">
<input type="hidden" id="_token" value="{{ csrf_token() }}">
..
</form>
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
156327 次 |
| 最近记录: |