Javascript 为 ajax (jQuery) 设置超时

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

Set timeout for ajax (jQuery)

javascriptjqueryhtmlcssajax

提问by James

$.ajax({
    url: "test.html",
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Sometimes successfunction works good, sometimes not.

有时success功能运作良好,有时则不然。

How do I set timeout for this ajax request? In example, 3 seconds, if time is out, then show an error.

如何为这个ajax请求设置超时?例如,3 秒,如果超时,则显示错误。

The problem is, ajax request freezes the block until finishes. If server is down for a little time, it will never end.

问题是,ajax 请求会冻结块直到完成。如果服务器停机一段时间,它永远不会结束。

回答by Intelekshual

Please read the $.ajaxdocumentation, this is a covered topic.

请阅读$.ajax文档,这是一个涵盖的主题。

$.ajax({
    url: "test.html",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000 // sets timeout to 3 seconds
});

You can get see what type of error was thrown by accessing the textStatus parameter of the error: function(jqXHR, textStatus, errorThrown)option. The options are "timeout", "error", "abort", and "parsererror".

您可以通过访问error: function(jqXHR, textStatus, errorThrown)选项的 textStatus 参数来查看抛出的错误类型。选项是“超时”、“错误”、“中止”和“解析器错误”。

回答by Brandon Boone

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

下面是一些示例,演示了在 jQuery 的新旧范式中设置和检测超时。

Live Demo

Live Demo

Promise with jQuery 1.8+

使用 jQuery 1.8+ 的承诺

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});?

jQuery <= 1.7.2

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatusparam (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

请注意,textStatus参数(或jqXHR.statusText)会让您知道错误是什么。如果您想知道失败是由超时引起的,这可能很有用。

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, 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", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

错误(jqXHR,textStatus,errorThrown)

请求失败时调用的函数。该函数接收三个参数:jqXHR(在 jQuery 1.4.x 中,XMLHttpRequest)对象、描述发生的错误类型的字符串和可选的异常对象(如果发生)。第二个参数(除了 null)的可能值是“超时”、“错误”、“中止”和“解析器错误”。当发生 HTTP 错误时,errorThrown 会接收 HTTP 状态的文本部分,例如“未找到”或“内部服务器错误”。从 jQuery 1.5 开始,错误设置可以接受函数数组。每个函数都会被依次调用。注意:对于跨域脚本和 JSONP 请求,不会调用此处理程序。

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

源代码:http: //api.jquery.com/jQuery.ajax/

回答by Martin Jespersen

You could use the timeoutsetting in the ajax options like this:

您可以使用timeoutajax 选项中的设置,如下所示:

$.ajax({
    url: "test.html",
    timeout: 3000,
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/

在此处阅读有关 ajax 选项的所有信息:http: //api.jquery.com/jQuery.ajax/

Remember that when a timeout occurs, the errorhandler is triggered and not the successhandler :)

请记住,当超时发生时,将error触发处理程序而不是success处理程序:)

回答by Rudolf Mühlbauer

use the full-featured .ajaxjQuery function. compare with https://stackoverflow.com/a/3543713/1689451for an example.

使用全功能的.ajaxjQuery 函数。以https://stackoverflow.com/a/3543713/1689451为例进行比较。

without testing, just merging your code with the referenced SO question:

无需测试,只需将您的代码与引用的 SO 问题合并:

target = $(this).attr('data-target');

$.ajax({
    url: $(this).attr('href'),
    type: "GET",
    timeout: 2000,
    success: function(response) { $(target).modal({
        show: true
    }); },
    error: function(x, t, m) {
        if(t==="timeout") {
            alert("got timeout");
        } else {
            alert(t);
        }
    }
});?