使用 jQuery AJAX 捕获 404 状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10931270/
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
Capture 404 status with jQuery AJAX
提问by Alan2
I have this code:
我有这个代码:
$.ajax({ cache: false,
url: "/Admin/Contents/GetData",
data: { accountID: AccountID },
success: function (data) {
$('#CityID').html(data);
},
error: function (ajaxContext) {
alert(ajaxContext.responseText)
}
});
I am still confused about the ajaxContext and how to capture 404 return codes. However I have another question. I am reading something about coding with success and fail and no longer using error in the recent versions of jQuery.
我仍然对 ajaxContext 以及如何捕获 404 返回码感到困惑。不过我还有一个问题。我正在阅读有关成功和失败的编码,并且不再在最近版本的 jQuery 中使用错误。
So should I change my code to use done and fail. How then could I check for a 404?
所以我应该改变我的代码来使用 done 和 fail。那我怎么能检查404呢?
回答by JayTee
Replace your error function as follows...
替换您的错误功能如下...
error:function (xhr, ajaxOptions, thrownError){
if(xhr.status==404) {
alert(thrownError);
}
}
回答by BenM
404 erros will be handled by the anonymous function hooked up to the error
property. Anything other than a successful HTTP request to the URL (i.e. 2xx) will trigger the error method. The following will work for your purpose:
404 错误将由连接到该error
属性的匿名函数处理。除了对 URL 的成功 HTTP 请求(即 2xx)之外的任何事情都会触发错误方法。以下将适用于您的目的:
error : function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status == 404 || errorThrown == 'Not Found')
{
console.log('There was a 404 error.');
}
}
When they refer to removing the success
and error
functions in the jQuery documentation, they're referring to those of the jqXHR class, not the properties of $.ajax()
.
当他们提到删除jQuery 文档中的success
和error
函数时,他们指的是 jqXHR 类的那些,而不是$.ajax()
.