Facebook Style AJAX Search

▼魔方 西西 提交于 2019-11-28 18:29:47

the method you are referring to is called "Debouncing"

I usually have a "Debounce" function at the bottom of all my scripts

var debounce=function(func, threshold, execAsap) {
    var timeout;
    return function debounced () {
        var obj = this, args = arguments;
        function delayed () {
            if (!execAsap)
                func.apply(obj, args);
            timeout = null; 
        };
        if (timeout)
            clearTimeout(timeout);
        else if (execAsap)
            func.apply(obj, args);
        timeout = setTimeout(delayed, threshold || 100); 
    }; 
};

And then whenever I do anything that will benefit from a debounce I can use it generically

So your code would be re-written as

$("#s").keyup(debounce(function() {
    var searchbox = $(this).val();
    var dataString = 's='+ searchbox;
    if(searchbox!='') {
        $.ajax({
                type: "POST",
                url: "/livesearch.php",
                data: dataString,
                cache: false,
                success: function(html){
                        $("#display").html(html).show();
                }
        });
    } else {return false; }  
}
,350 /*determines the delay in ms*/
,false /*should it execute on first keyup event, 
       or delay the first event until 
       the value in ms specified above*/
));

Another option would be to start searching after 2/3 characters. Waiting for 1 second before making every request doesn't look good to me. Also try to send very less data back to server which might also make the request and response faster.

You could have a JSON object sitting somewhere and searching that instead of searching the database multiple times. It won't bring too much overhang, as long as it's not a list of 1,000 friends or something.

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