Throttling an ajax livesearch function

别来无恙 提交于 2019-12-13 00:27:34

问题


I would like to throttle the following ajax live search function I wrote.

I made it so that requests are only sent if a minimum of 2 characters are entered. I also want to throttle the ajax for a quarter of a second to give the user a chance to type what they want. I wrapped the ajax in a setTimeout function, but that didn't work.

        $('#search').keyup(function() {
            var string = $(this).val();
            if (string.length >= 2) {
                $.ajax({
                    'type': 'GET',
                    dataType: 'html',
                    'url': url,
                    'success': function(data){
                                    // show the search data
                    }
                });                                             
            } else if (string.length <= 1) {
                        // restore page content as of when it was loaded
            }
        });

Another thing I should ask, I should probably cache the results of the ajax, no?


回答1:


Just the code inside if (string.length >= 2) :

var elem = $(this);
// save newest search
elem.data('search',search)
// clear pending searches
.clearQueue().stop()
// waits
.delay(250)
// runs search
.queue(function() {
    $.ajax({
        'type': 'GET',
        dataType: 'html',
        'url': url,
        'success': function(data){

        // check if can be run
        if(elem.data('search') != search)
            return;

                // show the search data
        }
    });
});



回答2:


Take a look at the source code for (or consider using) Jquery Autocomplete It does pretty much exactly what you want, it only submits data after a pause to make sure the user is done and it has a cache, amongst other features.



来源:https://stackoverflow.com/questions/6964501/throttling-an-ajax-livesearch-function

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