【问题标题】:How to set up ajax time out?如何设置ajax超时?
【发布时间】:2011-11-08 22:54:42
【问题描述】:

我有这段代码可以在 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";
            }

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

【问题讨论】:

    标签: javascript ajax timeout settimeout


    【解决方案1】:

    应该解决这个问题:

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

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

    另一种方法是使用jQuery.ajax,这样库就会处理它。

    您的代码如下所示:

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

    【讨论】:

    • 为了简洁起见,我将这个 setTimeout 函数命名为:var xmlto = setTimeout(...),然后在得到答案时将其清除:clearTimeout(xmlto);因为让它运行或再次调用 ajax 可能会造成一些混乱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 2011-07-10
    • 2013-10-06
    • 2019-06-25
    • 2011-08-09
    相关资源
    最近更新 更多