How to cancel/abort jQuery AJAX request?

后端 未结 8 2031
时光说笑
时光说笑 2020-11-22 09:30

I\'ve an AJAX request which will be made every 5 seconds. But the problem is before the AJAX request if the previous request is not completed I\'ve to abort that request and

8条回答
  •  囚心锁ツ
    2020-11-22 10:25

    jQuery: Use this as a starting point - as inspiration. I solved it like this: (this is not a perfect solution, it just aborts the last instance and is WIP code)

    var singleAjax = function singleAjax_constructor(url, params) {
        // remember last jQuery's get request
        if (this.lastInstance) {
            this.lastInstance.abort();  // triggers .always() and .fail()
            this.lastInstance = false;
        }
    
        // how to use Deferred : http://api.jquery.com/category/deferred-object/
        var $def = new $.Deferred();
    
        // pass the deferrer's request handlers into the get response handlers
        this.lastInstance = $.get(url, params)
            .fail($def.reject)         // triggers .always() and .fail()
            .success($def.resolve);    // triggers .always() and .done()
    
        // return the deferrer's "control object", the promise object
        return $def.promise();
    }
    
    
    // initiate first call
    singleAjax('/ajax.php', {a: 1, b: 2})
        .always(function(a,b,c) {console && console.log(a,b,c);});
    
    // second call kills first one
    singleAjax('/ajax.php', {a: 1, b: 2})
        .always(function(a,b,c) {console && console.log(a,b,c);});
        // here you might use .always() .fail() .success() etc.
    

提交回复
热议问题