Laravel - 如何返回json错误消息?
问题描述:
我刚刚添加了x-editable到我目前的Laravel项目。它工作得非常好,但我有一个问题返回错误消息。Laravel - 如何返回json错误消息?
当控制器能够保存请求时,我得到'成功'! 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);
}
});
亲切的问候。
答
我不熟悉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(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
回调必须返回一个代表错误信息的字符串。
希望得到这个帮助!
你可以尝试打印回应吗? – AShly
您可以将此块放在try catch上,并在catch上返回错误响应。 – Matheus