我在检查请求是否为ajax时遇到了问题。这是我的密码:
路由
Route::post('cookies-alert', 'CookiesController@weUseCookies')->name('cookies.weuse');
控制器
namespace app\Http\Controllers;
use Illuminate\Http\Request;
class CookiesController extends Controller
{
public function weUseCookies(Request $request)
{
if($request->ajax()){
return response()->json(['status' => 'successful']);
}else{
return response()->json(['status' => 'error']);
}
}
}
表单(使用Laravel集体,它自动创建_token)
{{ Form::open(['route' => ['cookies.weuse', ''], 'method' => 'POST', 'id' => 'cookie-form']) }}
....
<button type="submit">Ok</button>
{{ Form::close() }}
还有js
$('#cookie-form').on('submit', function(e){
e.preventDefault();
// .....
$.ajax({
url: url,
method: 'POST',
dataType: 'JSON',
data: data
}).done( function (response) {
var res = response;
if( res.status == 'successful' ){
console.log(res.status);
}else{
showError('error :(');
}
});
});
我试着用另一种方式
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'JSON',
success: function (data) {
console.log(data);
}
});
并使用来自https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js的jQuery3.2.1
但它总是从我的控制器返回“错误”。
我也尝试像Request::ajax()一样使用这,但是它跳过if{}并从我的控制器转到option {}选项。
我做错什么了?
我的代码工作在本地,但不在服务器上。
发布于 2018-05-08 14:10:15
laravel使用X请求-带有http头来检查传入的请求是否是ajax,还必须将@csrf字段添加到表单中:
$.ajax({
url: url,
type: 'POST',
// add _token field for csrf protection
data: {
_token : ''
},
dataType: 'JSON',
// add x-forwarded-with also add X-CSRF-TOKEN header for csrf protection
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': ..,
}
});
或者您可以使用axios,因为laravel可以更好地使用它:
axios({
method: 'POST',
url: 'url',
data: {
_token: 'token',
},
responseType: 'json',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': 'token,
}
}
发布于 2019-03-29 04:39:13
Request::wantsJson()
--它也在使用axios。
发布于 2020-03-15 03:51:41
您需要像app.js中的bellow一样设置标头
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
window.Vue = require('vue');
https://stackoverflow.com/questions/50242814
复制相似问题