1

I am trying to achieve an Ajax search/autocomplete as user types in. Here is my code:

$('#productSearch').live('keyup',function(){
    var searchterm = encodeURIComponent($('#productSearch').val());
    $('.ajax-search-results').load('/ajax/search.php?type=product&s=' + searchterm);

});

The problem is that results are not consistent with the input value, I have no idea why, but when I type too fast (too fast for handling the .load() maybe?) the results at end are not consistent (not what I expect) if i type in slowly, it works perfectly.

Can someone tell me how can I come over this situation?

  • I thought about disabling function until the load is done, but that would mean also that i will lose what the user has typed until the operation is done?
4

1 回答 1

1

这通常通过一个小的超时来修复,以便在用户快速键入时不会将请求堆叠在一起并为每个键执行 ajax,如果执行常规 $.ajax 调用,则通过中止先前的调用(abort()XHR不太容易带负载()):

var timer;

$(document).on('keyup', '#productSearch',function(){
    clearTimeout(timer);
    timer = setTimeout(function() {
        var searchterm = encodeURIComponent($('#productSearch').val());
        $('.ajax-search-results').load('/ajax/search.php?type=product&s=' + searchterm);
    }, 300);
});
于 2012-11-03T12:41:58.193 回答