Php Laravel-如何在出现错误时返回json错误消息?

Php Laravel-如何在出现错误时返回json错误消息?,php,json,laravel,x-editable,Php,Json,Laravel,X Editable,我刚刚将x-editable添加到我当前的Laravel项目中。它工作得非常好,但是我在返回错误消息时遇到问题 当控制器能够保存请求时,我得到一个“成功!”json消息。那很好。但当我有错误时,我不会得到“错误!”消息正如您所看到的,当$article->save()未成功时,我触发了错误消息 我做错了什么 控制器: $article->$input['name'] = $input['value']; if( $article->save() ){ // this wor

我刚刚将x-editable添加到我当前的Laravel项目中。它工作得非常好,但是我在返回错误消息时遇到问题

当控制器能够保存请求时,我得到一个“成功!”json消息。那很好。但当我有错误时,我不会得到“错误!”消息正如您所看到的,当$article->save()未成功时,我触发了错误消息

我做错了什么

控制器:

$article->$input['name'] = $input['value'];

if( $article->save() ){
    // this works
    return response()->json(array('status'=>'success', 'msg'=>'Success!.'), 200);
} 

else{
    // this does not work
    return response()->json(array('status'=>'error', 'msg'=>'Error!'), 500);
}
$(".xeditable").editable({
    success: function(response) {
        console.log(response.msg);
    },
    error: function(response) {
        // console says, that response.msg is undefinded
        console.log(response.msg);
    }
});
视图中的JavaScript:

$article->$input['name'] = $input['value'];

if( $article->save() ){
    // this works
    return response()->json(array('status'=>'success', 'msg'=>'Success!.'), 200);
} 

else{
    // this does not work
    return response()->json(array('status'=>'error', 'msg'=>'Error!'), 500);
}
$(".xeditable").editable({
    success: function(response) {
        console.log(response.msg);
    },
    error: function(response) {
        // console says, that response.msg is undefinded
        console.log(response.msg);
    }
});

亲切问候。

我不熟悉
x-editable
,但如果出现错误,请尝试将响应代码从
500
更改为
200
,然后在javascript中更改

$(".xeditable").editable({
    success: function(response) {
        if (response.status == 'error') {
            console.log('error: ' + response.msg);
        }
        else {
            // do stuff for successful calls
            console.log('success: ' + response.msg);
        }
    },
    error: function(xhr, status, error) {
        console.log('server error: ' + status + ' ' + error);
    }
});

error
回调中,传递的
response
参数是jqXHR()。为了访问JSON响应,您可以像下面的代码一样访问
responseJSON
属性

$(".xeditable").editable({
  success: function(response) {
    console.log(response.msg);
    // Must return nothing.
  },
  error: function(response) {
    // The JSON object stored in responseJSON property.
    console.log(response.responseJSON.msg);

    // Must return a string, represent the error message.
    return response.responseJSON.msg;
  }
});
正如X-editable文档中指出的那样,
错误
回调必须返回表示错误消息的字符串


希望这有帮助

您可以尝试打印响应吗?您可以将此块放在try-catch上,并在catch上返回错误响应。