JQuery.ajax (): cancel slow queries

I created a life cycle using the jQuery.ajax () method. In each keyup event, it receives new result data from the server.

The problem is that when I type very fast, for example, “foobar” and the GET request “fooba” take longer than the request “foobar”, the results of “fooba” are shown.

It seems to me that it is impossible to handle this with a timeout parameter.

Does anyone know how to solve this?

+5
source share
6 answers

You can save the .abort()last request when starting a new one, for example:

var curSearch;
$("#myInput").keyup(function() {
  if(curSearch) curSearch.abort(); //cancel previous search
  curSearch = $.ajax({ ...ajax options... }); //start a new one, save a reference
});

$.ajax() XmlHttpRequest, , , .

+7

, . - :

var counter = 0, lastCounter = 0;
function doAjax() {
  ++counter;
  jQuery.ajax(url, function (result) {
    if (counter < lastCounter)
      return;
    lastCounter = counter;
    processResult(result);
  });
}
+1
0

, . , .

0

, ajax KeyUp. , - , , , .

, :

var ajaxTimeout;

function doAjax() {
     //Your actual ajax request code
}


function keyUpHandler() {
    if (ajaxTimeout !== undefined) 
        clearTimeout(ajaxTimeout);

    ajaxTimeout = setTimeout(doAjax, 200);
}

, , .

: , ().

...
var fun = function() { doAjax(params...) };
ajaxTimeout = setTimeout(fun, 200);
0

- ajax, :

http://plugins.jquery.com/project/ajaxqueue

or http://www.protofunc.com/scripts/jquery/ajaxManager/

EDIT: Another option, examine the Autocomplete plug-in module and emulate it. (There are several Autocomplete as well as one in the jquery user interface OR just implement Autocomplete if it suits your needs.

0
source

All Articles