开发者

Handling successive Ajax requests - JQUERY

I have a search textbox where upon a keypress an AJAX call is made to return search results for the entered text. This results in an AJAX call being made for every single keypress.

For example if I type in airport:

I get 7 ajax requests each searching for a, ai, air, airp, airpo, airpor, airport respectively - however the problem is that they might all start one after the other but don't necessarily end in the same order 开发者_运维技巧so more often than not I receive results in the wrong order i.e I might have written airport and received the result for airport only to receive the result for airpo later on.

How do I handle this in jQuery here?

Update:

There is a timer delay of 3 seconds - but the issue is in ensuring that when one AJAX request is made, another Request when made cancels out the previous request and so forth.

How could I do this in code?


Fire the ajax call on a delay - use this in conjunction with the abort() code 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);
});


Sending a lookup request at every keystroke is generally a bad idea - I'd suggest instead that you send at short intervals (ie. send the textbox value every 3 seconds or so).

Further, to prevent the asynchronous returns, you could have a flag to keep track of a request's state, so that only 1 can be active at any one time (eg. set on send, cleared on return). This would effectively render your lookups synchronous.


EDIT: Added sample code

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;
        }
    });
}


You can cancel AJAX requests:

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

x.abort()

So if you want to send a new request before the previous one has returned, abort() the first one.


  1. Build an "ajax queue" in jquery... use it to ensure your requests go in order. The below address has a great example near the bottom:

    AJAX Streamlining techniques?

  2. Extend the functionality of these queue, to handle Delay and Abort mechanics like the answers above.

    If another request is submitted to the queue before the delay is over, abort the queued request.

Suggestion: add the functionality of delay and abort mechanics properly to the queue so that the values can be requested when you post a request to the queue, like params, that way your queue plugin remains reusable outside this need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜