javascript 如何设置ajax超时?

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

How to set up ajax time out?

javascriptajaxtimeoutsettimeout

提问by buzz3110

I have this code to time out ajax call after 40 secs:

我有这个代码在 40 秒后超时 ajax 调用:

if (xmlhttp) {
    xmlhttp.open("GET", MY_SERVLET, true);              xmlhttp.onreadystatechange = showResults;               
    xmlhttp.send(null);
    var httpTimeOut=setTimeout("ajaxTimeout();",40000);
            }

        function ajaxTimeout() {
            xmlhttp.abort();
        document.getElementById('errorShow').innerHTML = "Request Timed out";
            }

However I am unable to test this due to environment constraints at my place. Can anyone please tell if this is correct or any modifications are required??

但是,由于我所在的环境限制,我无法对此进行测试。谁能告诉我这是正确的还是需要任何修改?

回答by Nemoden

Should fix that:

应该解决这个问题:

if (xmlhttp) {
    xmlhttp.open("GET", MY_SERVLET, true);
    xmlhttp.onreadystatechange = showResults;               
    xmlhttp.send(null);
    setTimeout(function() {  xmlhttp.abort()  },40000);

since ajaxTimeoutfunction can't "see" xmlhttpvariable, but we can use anonymous function to have access to local variables.

由于ajaxTimeout函数不能“看到”xmlhttp变量,但我们可以使用匿名函数来访问局部变量。

Yet another approach is to use jQuery.ajaxso the library would take care of it.

另一种方法是使用,jQuery.ajax以便图书馆处理它。

Your code would look like so:

您的代码如下所示:

$.ajax({
    url: MY_SERVLET,
    async: true,
    timeout: 40000,
    success: function(args) { 
        // on success code
    }
})