jQuery的AJAX搜索去抖

jQuery的AJAX搜索去抖

问题描述:

我建立一个生活搜索的网站,将返回基于什么类型的用户的结果。我只希望当用户完成输入的请求被发送。

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.

我已经尝试过使用定时器,甚至防抖方法从underscore.js几个实现,但我总是似乎得到了类似的结果。

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.

这是用下划线JS我目前的执行

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?

也许你的用户就无法足够快。将参数_去抖函数长于100ms的在你的例子:(见规格: _.debounce(函数,等待,[即时])

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