如何设置ajax超时

How to set up ajax time out?

本文关键字:ajax 超时 设置 何设置      更新时间:2023-09-26

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

然而,由于我所在的环境限制,我无法测试这一点。谁能告诉我这是正确的还是需要修改??

应该修复:

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
    }
})