Abort JSONP ajax request with jQuery

前端 未结 5 1144
说谎
说谎 2020-12-28 19:36

I\'m using a JSONP ajax call to load some content from a different domain, and all this stuff is executed if the user causes a \"mouseover\" on a button.

I can captu

5条回答
  •  鱼传尺愫
    2020-12-28 19:59

    Trevor Burnham's answer is pretty good, but instead of tracking a request count, you should just compare the request to the XHR parameter, like so;

    doRequest: function() {
        this._freeRequest();
    
        this._request = $.getJSON(url + params + '&callback=?', function(response, status, xhr) {
            if (this._request !== xhr) return; // aborted
    
            // success
        }.bind(this)).done(this._freeRequest.bind(this));
    }
    
    _freeRequest: function() {
        if (this._request) {
            delete this._request;
        }
    }
    

    Calling doRequest again or _freeRequest once before the previous request has completed, will result in the "abortion" of said request by causing the if (this._request !== xhr) line to become true, since this._request will either be deleted or another request altogether.

提交回复
热议问题