jQuery 显示 JSON 返回的错误信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15006178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
To show JSON returned error message
提问by VVR147493
I needs to show the Jsonreturned message.
我需要显示Json返回的消息。
In the controller, an exception is thrown and caught in a catch block. I am returning the fault error message.
在控制器中,抛出异常并在 catch 块中捕获。我正在返回故障错误消息。
In Ajax, the successpart always executes. But if it is an error from my webservice, I don't want to execute the normal; instead I want to show an error message.
在Ajax 中,成功部分总是会执行。但是如果是我的webservice错误,我不想执行正常的;相反,我想显示一条错误消息。
How I can achieve this?
我怎么能做到这一点?
My code below:
我的代码如下:
Controller
控制器
[HttpPost]
public JsonResult DeleteClientRecord()
{
bool result = true;
try
{
result = ClientCRUDCollection.DeleteClient(deleteClientId);
}
catch (Exception ex)
{
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
return Json(new { result }, JsonRequestBehavior.AllowGet);
}
AJAX Call
AJAX 调用
$("#YesDelete").click(function () {
$.ajax({
type: "POST",
async: false,
url: "/Client/DeleteClientRecord",
dataType: "json",
error: function (request) {
alert(request.responseText);
event.preventDefault();
},
success: function (result) {
// if error from webservice I want to differentiate here somehow
$("#Update_" + id).parents("tr").remove();
$('#myClientDeleteContainer').dialog('close');
return false;
}
});
});
Please can anyone help me on this.
请任何人都可以帮助我。
回答by Dave Alperovich
[HttpPost]
public JsonResult DeleteClientRecord()
{
bool result = true;
try
{
result = ClientCRUDCollection.DeleteClient(deleteClientId);
}
catch (Exception ex)
{
return Json(new { Success="False", responseText=ex.Message});
}
return Json(new { result }, JsonRequestBehavior.AllowGet);
}
回答by Hala
to show error message, you should add error scope after success scope in AJAX call like this:
要显示错误消息,您应该在 AJAX 调用中的成功范围之后添加错误范围,如下所示:
$("#YesDelete").click(function () {
$.ajax({
type: "POST",
async: false,
url: "/Client/DeleteClientRecord",
dataType: "json",
error: function (request) {
alert(request.responseText);
event.preventDefault();
},
success: function (result) {
// if error from webservice I want to differentiate here somehow
$("#Update_" + id).parents("tr").remove();
$('#myClientDeleteContainer').dialog('close');
return false;
}
error: function (xhr) {alert(JSON.parse(xhr.responseText).Message); }
});
});