使用 jQuery AJAX 显示正确的错误消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8041148/
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
Show proper error messages with jQuery AJAX
提问by Cameron
Currently if I have an error with an ajax request such as submitting a form (I'm using ASP.NET MVC 3) it will show something like 'Internal Server Error'.
目前,如果我在 ajax 请求中出现错误,例如提交表单(我使用的是 ASP.NET MVC 3),它将显示类似“内部服务器错误”的内容。
But if I do the submit without using Ajax then .net will show the actual server error.
但是如果我在不使用 Ajax 的情况下进行提交,那么 .net 将显示实际的服务器错误。
Any ideas on how I could perhaps get the error to show? So my users can report the problem instead of only being able to say 'internal server error'
关于如何显示错误的任何想法?所以我的用户可以报告问题而不是只能说“内部服务器错误”
Thanks
谢谢
回答by Manse
Although I wouldnt recommend showing the user an error number with the actual response error message this is how you can do this by adding the error
callback
尽管我不建议向用户显示带有实际响应错误消息的错误编号,但您可以通过添加error
回调来执行此操作
error: function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
xhris XmlHttpRequest.
xhr是 XmlHttpRequest。
readyStatevalues are 1:loading, 2:loaded, 3:interactive, 4:complete.
readyState值为 1:loading, 2:loaded, 3:interactive, 4:complete。
statusis the HTTP status number, i.e. 404: not found, 500: server error, 200: ok.
status是 HTTP 状态号,即 404:未找到,500:服务器错误,200:正常。
responseTextis the response from the server - this could be text or JSON from the web service, or HTML from the web server.
responseText是来自服务器的响应 - 这可以是来自 Web 服务的文本或 JSON,或者来自 Web 服务器的 HTML。
回答by BNL
This code will replace the current page's contents with the error that came back from the ajax request.
此代码将使用从 ajax 请求返回的错误替换当前页面的内容。
jQuery(document).ajaxError(function (event, request, settings) {
if (request.status === 500) {
$(document.body).html(request.responseText);
} else if (request.status === 401) {
// redirect to login, 401 means session is expired.
window.location.href = "login page url";
}
});