【问题标题】:Javascript Ajax post Method not Working in Laravel 5Javascript Ajax post 方法在 Laravel 5 中不起作用
【发布时间】:2018-04-21 02:20:31
【问题描述】:

我正在使用 JavaScript 研究 Ajax,并希望在 Laravel 5.4 中创建一个 Ajax 发布方法。这些是我的文件...

路线

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(内部服务器错误)

感谢您的帮助并忽略错误的编码。 :)

【问题讨论】:

    标签: javascript ajax laravel laravel-5.4


    【解决方案1】:

    我发现我的错误是缺少csrf_token,所以我添加:

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

    到页面标题并在javascript中获取csrf_token并将其发送到post route by:
    xhr.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content );
    和它的工作。希望对其他人有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 2015-06-06
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      相关资源
      最近更新 更多