How to cancel a JSON request when sending a new jsonrequest to the server

When a user enters something into a text field to autofill work with json, he makes a lot of requests to the server. How can I stop an old query when creating a new query in jQuery?

+5
source share
2 answers

I think you run those json requeston top of the object XMLHttpRequestor, in other words, use .ajax(). You can generally cancel the ajax request using .abort().

var xhr = $.ajax({});

// somewhere else
if(xhr)
   xhr.abort();

since it .ajax()returns the original event XHRthat you can save in this place and abort this request. Of course, you would need to create some of the “query logic” to process this material. Example:

var xhrmanager = function() {
    var requests = [],
        self     = {};

    self.create  = function(params, cb){
        if(typeof params === 'object') {// additional checks here
           var xhr = $.ajax($.extend({
               url:      '/path/script.pl',
               dataType: 'json',
               type:     'GET',
               success:  function(data, status, req){
                    if(typeof cb === 'function')
                       cb.apply(this, [data]);                        
               },
               complete: function(req, status) {
                    var pos = $.inArray(req, requests);

                    if(pos > -1)
                       requests.splice(pos, 1)
               }
           }, params || {}));
        }
    };
    self.clearAll = function(){
        for(var i = 0, len = requests.length; i < len; i++){
           requests[i].abort();
        }
    };

    return self;
};

:

var json_requests = xhrmanager();

json_requests.create({
   data:  'some=data'
}, function(data) {
   // do something
});

json_requests.clearAll();
+3

, , : (, 100 ) . reset .

.

var timeout;
var textBox = $('#textbox');
textBox.change(function() {
    if (timeout) {
        clearTimeout(timeout);
    }
    var callingMethod = /* insert your method for the request */;
    timeout = setTimeout(callingMethod, 100);
});

: . , , (-: ). , , , . , .

.

var request;
function DoMagicThing() {
    if (request) {
        request.abort();
        request = null;
    }

    request = $.ajax({
        /* insert options here */,
        complete = function() {
            request = null;
        }
    });
}
0

All Articles