繁体   English   中英

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

[英]Laravel - How to return json error message on error?

我刚刚将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);
}

视图中的JavaScript:

$(".xeditable").editable({
    success: function(response) {
        console.log(response.msg);
    },
    error: function(response) {
        // console says, that response.msg is undefinded
        console.log(response.msg);
    }
});

亲切的问候。

error回调时,传递的response参数为jqXHR( jQuery XMLHttpRequest )。 为了访问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可编辑文档所指出的, error回调必须返回代表错误消息的字符串。

希望有帮助!

我不熟悉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);
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM