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
小弟新手,请大神多多指教

阅读 3.5k
2 个回答

public function operate(Post $post)
这个地方应该限制类型整形 而不是post对象 或者你把他去掉应该就可以了
public function operate($post) 这样写

parser error 意思是 解析错误,你最有可能的问题是,后台返回的数据不是标准的json各式。
通过分析你的代码发现

你用以下的验证规则
$this->validate(request(), [
    "status" => 'required|in:-1,1',
]);
如果验证失败,相应的响应会自动生成。问题就出在这了。因为这个响应并不是你期望的json。可手工对这个规则处理错误信息,返回自定义的错误格式,具体请参考 laravel验证手册。

如果解决了您的问题,请采纳

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题