admin管理员组

文章数量:1415684

I've an ajax call to set of urls to get html content. But some of the urls are taking long time to get the content, i'm okay to skip those which take more than say 1 sec.

    for (url in list) {
    $.ajax({
        'url': url,
        type: 'get',
        timeout: 1000,
        success: function () {
            //doSomething
        },
        plete: function () {
            //what to write?
        }
    });

}

Can you help me in how to abort the ajax call if it timeouts and execute the plete function.

Lemme know if i'm not clear. Thanks

I've an ajax call to set of urls to get html content. But some of the urls are taking long time to get the content, i'm okay to skip those which take more than say 1 sec.

    for (url in list) {
    $.ajax({
        'url': url,
        type: 'get',
        timeout: 1000,
        success: function () {
            //doSomething
        },
        plete: function () {
            //what to write?
        }
    });

}

Can you help me in how to abort the ajax call if it timeouts and execute the plete function.

Lemme know if i'm not clear. Thanks

Share Improve this question edited Sep 13, 2012 at 17:17 Sushanth -- 55.8k9 gold badges69 silver badges107 bronze badges asked Sep 13, 2012 at 16:54 RaviTejaRaviTeja 1,0263 gold badges14 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

First, change $.ajax(function() { to $.ajax({, because the argument you are trying to use is an object, not a function.

Since you specify a timeout in your options object, if the page doesn't respond in time, the ajax method will tell your error function so, as long as you specify one.

$.ajax({
  'url': yourUrlHere,
  success: function(){ /*do stuff*/ },
  timeout: 1000,
  error: function(xhr, status, err){ 
    //status === 'timeout' if it took too long.
    //handle that however you want.
    console.log(status,err); 
  }
});

See the documentation for $.ajax here, as it has a pretty good explanation of the function.

You can abort the Request if that happens and go on to the next one..

var ajaxRequests = null;
for(url in list){
    var newRequest = $.ajax({
    type: 'GET',
    url: url,
    data: '{}',
    dataType: 'json',
    beforeSend: function() {
        var r = ajaxRequest;
        if (r != null && r != undefined) {
            r.abort();
        }
    },
    success: function(result) {
        // what has to be done if the ajax request es through
    },
    plete: function() {
        ajaxRequests = null;
    }
    ajaxReqs = newRequest;
}

本文标签: javascriptJquery ajax call timeoutStack Overflow