我正在研究使用JavaScript的Ajax,并希望在Laravel5.4中创建一个Ajax post方法。这些是我的文件..。
路由
Route::group(['prefix' => 'admin'],function(){
Route::post('/ccat','PagesContrpllerController@ccat')->name('ccat');
Route::resource('/products' , 'ProductController');
});
ProductCategoryController
public function ccat(Request $request){
return 'hello this is post method';
}
JavaScript
function sendfunc(name , level , parent){
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status==200) {
console.log(this.responseText);
}
}
xhr.open("POST", "ccat", true);
xhr.setRequestHeader("Content-type", "application/x-www-formurlencoded");
xhr.send("fname=Henry&lname=Ford");
}
我期望控制台中的'hello this is the post method'
,但它返回:
POST http://localhost:8000/admin/product/ccat 404 (未找到)
控制台中发生了什么?即使我将URL更改为:http://localhost:8000/admin/ccat`,它也会返回:
POST http://localhost:8000/admin/ccat 500 (内部服务器错误)
感谢您的帮助,并忽略了糟糕的代码。:)
发布于 2017-11-09 14:42:03
我发现了我的错误,那就是缺少csrf_token
,所以我添加:
<meta name="csrf-token" content="{{ csrf_token() }}" />
获取javascript
中的csrf_token
,并通过以下方式将其发送到post路由:
xhr.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content )
;
而且它起作用了。希望对其他人有用
https://stackoverflow.com/questions/47178985
复制相似问题