Jquery ajax search debounce

2019-05-30 13: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