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

跟風遠走 提交于 2019-12-06 12:23:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4439953/jquery-ui-autocomplete-how-do-you-start-an-asynchronous-process-and-quit-it-bef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!