jQuery ajax超时回调函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16533360/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:18:34  来源:igfitidea点击:

ajax timeout callback function

jqueryajax

提问by d-_-b

Is there a way to run a function if jQuery's $.ajax function hits it's timeout?

如果 jQuery 的 $.ajax 函数命中它,有没有办法运行一个函数timeout

i.e.

IE

$.ajax({
...
...
,timeout:1000(){do something if timeout)
...

});

回答by Dan-Nolan

$.ajax({
    ...
    timeout: 1000,
    error: function(jqXHR, textStatus, errorThrown) {
        if(textStatus==="timeout") {
           //do something on timeout
        } 
    }
});?

For more information check out the jQuery documentation:

有关更多信息,请查看 jQuery 文档:

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/



Edited

已编辑

It's been over a year since I initially answered this and the textStatuspossible values have changed to "success", "notmodified", "error", "timeout", "abort",or"parsererror". For error callbacks, only the last four statuses are possible.

自从我最初回答这个问题以来已经一年多了,textStatus可能的值已更改为"success", "notmodified", "error", "timeout", "abort","parsererror"。对于错误回调,只有最后四种状态是可能的。

Also you can now wire your error handlers through the returned JQuery deferred promise object's .failmethod:

此外,您现在可以通过返回的 JQuery 延迟承诺对象的.fail方法连接您的错误处理程序:

var promise = $.ajax({ timeout: 1000 });

promise.fail(function(jqXHR, textStatus) {
    if(textStatus==="timeout") {
        // handle timeout  
    }
});