簡體   English   中英

Javascript Ajax post方法在Laravel 5中不起作用

[英]Javascript Ajax post Method not Working in Laravel 5

我正在研究使用JavaScript的Ajax,並希望在Laravel 5.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(內部服務器錯誤)

感謝您的幫助,並忽略了錯誤的編碼。 :)

我發現我的錯誤是缺少csrf_token因此我添加:

<meta name="csrf-token" content="{{ csrf_token() }}" />  

到頁面標題,並在javascript獲取csrf_token並將其發送至發布路線,方法如下:
xhr.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content ) ;
和它的工作。 希望對別人有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM