鍍金池/ 問答/PHP/ laravel中ajax請求一直報parsererror錯誤

laravel中ajax請求一直報parsererror錯誤

laravel5.4中使用ajax請求控制器接口一直報錯
admin.js

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(".post-audit").click(function(){
    var status = $(this).attr("post-action-status");
    var post_id = $(this).attr("post-id");
    var _self = $(this);
    $.ajax({
        url: "/admin/post/"+post_id+"/operate",
        method: "POST",
        data: {"status": status},
        dataType:"json",
        success: function handleSuccess(data){
            console.log(data);
            //操作后該項不顯示
            //_self.parent().parent().remove();
        },
        error: function(xhr, type){
            console.log(type);
        }
    });
});

控制器

public function operate(Post $post)
    {
        return ['code'=>200,'msg'=>'測試'];
        /*$this->validate(request(), [
            "status" => 'required|in:-1,1',
        ]);

        $post->status = request('status');
        $post->save();
        return response()->json([
            'error' => 0,
            'msg' => ''
        ]);*/
    }

上面的請求瀏覽器控制臺一直提示parsererror:

clipboard.png

但是將返回數據寫在路由里又是正常的

Route::post('/admin/post/{post}/operate',function(){
    return ['code'=>200,'msg'=>'測試']; 
})->where('post','[0-9]+');

瀏覽器控制臺輸出:

clipboard.png
小弟新手,請大神多多指教

回答
編輯回答
挽歌

parser error 意思是 解析錯誤,你最有可能的問題是,后臺返回的數據不是標準的json各式。
通過分析你的代碼發(fā)現

你用以下的驗證規(guī)則
$this->validate(request(), [
    "status" => 'required|in:-1,1',
]);
如果驗證失敗,相應的響應會自動生成。問題就出在這了。因為這個響應并不是你期望的json??墒止@個規(guī)則處理錯誤信息,返回自定義的錯誤格式,具體請參考 laravel驗證手冊。

如果解決了您的問題,請采納

2018年5月23日 17:51
編輯回答
吢涼

public function operate(Post $post)
這個地方應該限制類型整形 而不是post對象 或者你把他去掉應該就可以了
public function operate($post) 這樣寫

2018年6月1日 06:45