开发者

How to set up ajax time out?

开发者 https://www.devze.com 2023-04-02 03:11 出处:网络
I have this code to time out ajax call after 40 secs: if (xmlhttp) { xmlhttp.open(\"GET\", MY_SERVLET, true);xmlhttp.onread开发者_运维技巧ystatechange = showResults;

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

if (xmlhttp) {
    xmlhttp.open("GET", MY_SERVLET, true);              xmlhttp.onread开发者_运维技巧ystatechange = 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??


Should fix that:

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

since ajaxTimeout function can't "see" xmlhttp variable, but we can use anonymous function to have access to local variables.

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

Your code would look like so:

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

精彩评论

暂无评论...
验证码 换一张
取 消