Jquery ajax search debounce

烂漫一生 提交于 2020-01-23 19:16:31

问题


I am building a live search for a website that will return results based on what the user types. I only want the request to be sent when the user has finished typing.

I have tried a few implementations using timers and even the debounce method from underscore.js but I always seem to be getting a similar result.

While I am typing, the request is delayed until I have finished typing. But then it seems to fire all the inputs as if they were queued. For example, if I type in "bikes" the results come back like:

b

bi

bik

bikes

As such, you get a stream of results for the search.

This is my current implementation using underscore js

$('#search_term').on('keyup', _.debounce(function (e) {

       $.ajax({
            type: "GET",
             url: "quicksearch.php",
            data: { search_term:$('#search_term').val()},
            success: function(msg){
              $('#quick_search_results').html(msg).slideDown();
            }
    });

}, 100));

Anyone have any ideas?


回答1:


Maybe your users cannot type fast enough. Set the wait parameter of the _.debounce function to be longer than the 100ms in your example: (see specs: _.debounce(function, wait, [immediate]).

$('#search_term').on('keyup', _.debounce(function (e) {
   $.ajax({
        type: "GET",
        url: "quicksearch.php",
        data: { search_term:$('#search_term').val()},
        success: function(msg){$('#quick_search_results').html(msg).slideDown();}
   });
}, 300)); // < try 300 rather than 100


来源:https://stackoverflow.com/questions/18986895/jquery-ajax-search-debounce

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