【发布时间】:2015-05-23 20:31:44
【问题描述】:
如果我有以下看法:
$.ajax({
url: '@PathHelper.FullyQualifiedApplicationPath(Request)' + 'Home/asdasd',
type: 'POST', dataType: 'json',
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
data: {
searchForIt: document.getElementById('searchValue').value
},
error: OnError,
success: function (data) {
// Do Stuff
}
});
而错误函数OnError为:
function OnError(xhr, errorType, exception) {
var responseText;
$("#dialog").html("");
try {
responseText = jQuery.parseJSON(xhr.responseText);
$("#dialog").append("<div><b>An error has occurred, please inform Paul Zahra quoting the following details:</b></div>");
$("#dialog").append("<div><b>" + errorType + " " + exception + "</b></div>");
$("#dialog").append("<div><u>Exception</u>:<br /><br />" + responseText.ExceptionType + "</div>");
$("#dialog").append("<div><u>StackTrace</u>:<br /><br />" + responseText.StackTrace + "</div>");
$("#dialog").append("<div><u>Message</u>:<br /><br />" + responseText.Message + "</div>");
} catch (e) {
responseText = xhr.responseText;
$("#dialog").html(responseText);
}
}
在控制器中如何设置 JSon 错误的参数,以便我可以提供自定义详细信息,例如“您输入了无效数据”。或“数据库有问题,请重试。”?;
OnError(xhr, errorType, exception)
附:在控制器中,为了让视图中的 ajax 认为发生了错误,我只是使用:
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
附言我知道以下内容,但它没有解释我如何从 mvc 控制器设置它。
"错误 类型:函数(jqXHR jqXHR,字符串 textStatus,字符串 errorThrown ) 请求失败时调用的函数。该函数接收三个参数:jqXHR(在 jQuery 1.4.x 中,XMLHttpRequest)对象,一个描述发生的错误类型的字符串和一个可选的异常对象(如果发生)。第二个参数(除了 null)的可能值是“timeout”、“error”、“abort”和“parsererror”。发生 HTTP 错误时,errorThrown 会接收 HTTP 状态的文本部分,例如“未找到”或“内部服务器错误”。
"为了向后兼容 XMLHttpRequest,jqXHR 对象将公开以下属性和方法:
readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
statusCode()
abort()"
【问题讨论】:
标签: c# jquery ajax json asp.net-mvc-4