如果连接超时,如何中止XMLHttpRequest?

时间:2010-10-14 14:24:57

标签: javascript timeout xmlhttprequest

我遇到了XMLHttpRequest的问题。如果没有Internet连接,我的请求不会超时,从而冻结浏览器。这是请求代码:

 var jsonData = new XMLHttpRequest();
 jsonData.open('GET', urltest, false);
 jsonData.Timeout = 100;
 jsonData.send(null);
 if(jsonData.status == 200) {
     alert(jsonData.statusText);
 }else{
     alert(jsonData.statusText);
 }

如果服务器没有响应,我该如何中止请求?

1 个答案:

答案 0 :(得分:0)

我对您的代码进行了一些更改,并在我做出更改的地方留下了一些评论来解释正在进行的操作。我希望它有所帮助!

var jsonData = new XMLHttpRequest();
jsonData.open('GET', urltest);/* I removed the false, because it kept the browser
waiting for the page to load to continue, and it didn't let it do other things
while it was still loading.*/
jsonData.Timeout = 100;
jsonData.send();
jsonData.onreadystatechange = function() {/*Each time readyState changes value,
                                            run this code.*/
    if (jsonData.readyState == 4) {/*When readyState is equal to 4,
                     the page has fully loaded.
                     Only run the code when it's 4,
                     not when it's still loading.*/
        if (jsonData.status == 200) {
            alert(jsonData.statusText);
        } else {
            alert(jsonData.statusText);
        }
        // More things to do when the page has fully loaded...
    }
}