jQuery UI Autocomplete: how do you start an asynchronous process and quit it before it finishes

StackOverflow https://stackoverflow.com/questions/4439953

Pergunta

I am using jQuery UI Autocomplete to build a search interface.

I have defined a custom function which returns search results and updates them automatically as keys are pressed however, sometimes this custom function doesn't complete before the next key is pressed (i.e. its still processing "Wash" when I have already written "Washi" (on the way to writing "Washington").

I would like every call to the autocomplete "source" event to cancel the previous function(Wash) and start the new function(Washi). With the next call cancelling function(Washi) and starting function (Washin) and so on.

How is this kind of thing done?

Foi útil?

Solução

You should be able to do something like this:

var lastXhr;
$( "#myAutocomplete" ).autocomplete({
    source: function( request, response ) {
        if (lastXhr) lastXhr.abort();
        lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
            if ( xhr === lastXhr ) {
                response( data );
            }
        });
    }
});

the lastXhr var stores the most current xhr request. If there is one set and the source function is called then it aborts the lastXhr request and makes a new one. When the ajax request returns if make sure that it matches the lastXhr, if not then it doesn't call the response() function.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top