Serial Ajax Request Processing - JQUERY

I have a search text box where, after pressing the key, AJAX is called to return the search results for the entered text. This results in an AJAX call for each keystroke.

For example, if I type airport:

I get 7 ajax requests, each of which is looking for a, ai, air, airp, airpo, airpor, airport, respectively - however, the problem is that they can all start one after another, but do not necessarily end in the same order most often I I get the results in the wrong order, i.e. I could write airportand get the result for airportjust to get the result for airpolater.

How do I handle this in jQuery here?

Update:

The timer delay is 3 seconds, but the problem is that when executing one AJAX request, another request, when it is made, cancels the previous request, etc.

How can I do this in code?

+3
source share
4 answers

Leave the ajax call on hold - use it in combination with the code abort()above:

var typeDelay = function(){
    var timer = 0;
    return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    }  
}();

$("#searchField").keypress(function(){
    typeDelay(function(){
        // your ajax search here, with a 300 ms delay...
    }, 300);
});
+3
source

Sending a search request each time you press a key is usually a bad idea - I would suggest sending it at short intervals instead (that is, sending a text box value every 3 seconds or so).

, , (, , ). .


EDIT:

var req = null;

function sendRequest (text)
{
    // Check for pending request & cancel it
    if (req) req.abort ();

    req = $.ajax ({
        // various options..
        success: function (data)
        {
            // Process data
            ...
            // reset request
            req = null;
        }
    });
}
+2

AJAX:

var x = $.ajax({
    ...
});

x.abort()

, , , () .

+1
  • "ajax queue" jquery... , . :

    AJAX?

  • , Delay Abort, .

    , .

Suggestion: Add the functionality of the delay and interrupt mechanics to the queue so that values ​​can be requested when sending a request to the queue, for example params, so your queue plugin remains reusable beyond this need.

0
source

Source: https://habr.com/ru/post/1723312/


All Articles