检查 jQuery ajax 请求的状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3163229/
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
Check status of a jQuery ajax request
提问by Seth Archer Brown
It seems that the success, error, and complete callbacks only fire when the ajax request is able to get some response from the server.
似乎只有当 ajax 请求能够从服务器获得一些响应时,才会触发成功、错误和完成回调。
So if I shut down the server the following error callback is not executed and the request fails silently.
因此,如果我关闭服务器,则不会执行以下错误回调,并且请求会以静默方式失败。
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});
What's the best way to throw an error when the server can't be reached at all.
当根本无法访问服务器时,抛出错误的最佳方法是什么。
Edit - From what I've tried and read it appears that jQuery's built in error handling doesn't work with JSONP, or dataType: "script". So I'm going to try setting a manual timeout.
编辑 - 从我尝试和阅读的内容来看,jQuery 的内置错误处理似乎不适用于 JSONP 或 dataType:"script"。所以我将尝试设置手动超时。
Edit - Did a little more research and it looks like not only does the ajax error callback not work, but you can't abort an ajax request with dataType script or jsonp, and those requests ignore the timeout setting.
编辑 - 进行了更多研究,看起来不仅 ajax 错误回调不起作用,而且您无法使用 dataType 脚本或 jsonp 中止 ajax 请求,并且这些请求会忽略超时设置。
There is an alternative - the jquery-jsonp plugin, but it uses hidden iframes which I'd rather avoid. So I've settled on creating a manual timeout as suggested below. You can't abort the request if it times out, which means the script may still load even after the timeout, but at least something will fire if the server is unavailable.
还有一个替代方案 - jquery-jsonp 插件,但它使用了我宁愿避免的隐藏 iframe。所以我决定按照下面的建议创建一个手动超时。如果超时,您将无法中止请求,这意味着即使超时后脚本仍可能加载,但如果服务器不可用,至少会触发某些内容。
采纳答案by Matthew Flaschen
You can use a setTimeout
, and clear it with clearTimeout
in the complete handler.
您可以使用setTimeout
, 并clearTimeout
在完整处理程序中清除它。
var reqTimeout = setTimeout(function()
{
alert("Request timed out.");
}, 5000);
var xhr = $.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
},
complete: function() {
clearTimeout(reqTimeout);
}
});
回答by Evadne Wu
jQuery.ajax already has a timeout
preference and it should call your error handler should the request time out. Check out the fantastic documentationwhich says — I'd quote it here, emphasis mine:
jQuery.ajax 已经有一个timeout
首选项,如果请求超时,它应该调用您的错误处理程序。查看精彩的文档,其中说 - 我在这里引用它,强调我的:
timeoutNumber
Set a local timeout (in milliseconds) for the request…
timeoutNumber
为请求设置本地超时(以毫秒为单位)...
and:
和:
error (XMLHttpRequest, textStatus, errorThrown) Function
A function to be called if the request fails. The function is passed three arguments: The 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", "notmodified" and "parsererror". This is an Ajax Event.
error (XMLHttpRequest, textStatus, errorThrown) Function
请求失败时调用的函数。该函数传递了三个参数:XMLHttpRequest 对象、一个描述发生的错误类型的字符串和一个可选的异常对象(如果发生了)。第二个参数(除 null 外)的可能值是"timeout"、"error"、"notmodified" 和 "parsererror"。这是一个 Ajax 事件。
回答by josepainumkal
error: function (jqXHR, textStatus, errorthrown) {
if (jqXHR.readyState == 0) {
//Network error, i.e. server stopped, timeout, connection refused, CORS, etc.
}
else if (jqXHR.readyState == 4) {
//HTTP error, i.e. 404 Not found, Internal Server 500, etc.
}
}
Use readyStateof XMLHttpRequest to determine the status of the ajax request. 'readyState' holds the status of the XMLHttpRequest.
使用XMLHttpRequest 的readyState来判断 ajax 请求的状态。'readyState' 保存 XMLHttpRequest 的状态。
- 0: request not initialized
- 1: server connection established
- 2: request received
- 3: processing request
- 4: request finished and response is ready
- 0:请求未初始化
- 1:服务器连接建立
- 2:收到请求
- 3:处理请求
- 4:请求完成,响应准备好
回答by Sphvn
You can use Jquery's AjaxSetup to handle your error handling.
您可以使用 Jquery 的 AjaxSetup 来处理您的错误处理。
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function () {
alert("success");
}, error: function () {
alert("error");
}
//AJAX SETUP "error"//
$.ajaxSetup({
"error": function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + ' ' + textStatus + ' ' + errorThrown); //however you want
}
});
回答by Skudd
If I remember correctly, jQuery throws exceptions. Thus, you should be able to work with a try { ... } catch() { ... }
and handle it there.
如果我没记错的话,jQuery 会抛出异常。因此,您应该能够使用 atry { ... } catch() { ... }
并在那里处理它。
回答by Koerr
in ie8,can use:
在ie8中,可以使用:
success: function(data, textStatus, XMLHttpRequest) {
if("success"==textStatus&&XMLHttpRequest){
alert("success");
}else{
alert("server down");
}
}
but it's can't work on chrome,firefox... i tried
但它不能在 chrome、firefox 上工作……我试过了