AJAX 错误作为成功返回。如何从 ASP.NET MVC 返回 JSON 错误?你能告诉我我做错了什么吗?谢谢。
[HttpPost]
public JsonResult Register(int EventID)
{
try
{
// code
return Json(new { success = true, message = "Thank you for registering!" });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
$.ajax({
url: "@Url.Action("Register", "Home")",
type: "post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(postData),
success: function(data) {
},
error: function (data) {
}
});
最佳答案
仅当 HTTP 响应代码不是 HTTP 200 Ready
时,才会执行 error
函数。您在服务器端处理错误并返回正确的响应,该响应将由 AJAX 调用中的 success
函数获取。相反,请在 JSON 中使用 status
变量并在客户端处理它:
success: function(data) {
if (typeof data == "string")
data = JSON.parse(data);
if (data.success) {
// Code if success.
} else {
// Code if error.
}
},
来自docs (向下滚动到错误
部分):
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides
null
) are"timeout"
,"error"
,"abort"
, and"parsererror"
. When an HTTP error occurs,errorThrown
receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, theerror
setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
关于javascript - AJAX 错误返回为成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37187699/