Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

javascript - Facebook Style AJAX Search

I've created a Facebook style ajax search for my site where as you type it will bring up the results in a nice list below your search.

$("#s").keyup(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; }  
});

$("body").click(function() {
        $("#display").hide();
});

The problem with this is it's a little ineffective as the user will type a word for example "football". This will carry out 8 requests to the server. What would be a more effective way to do this? ideally i think it should store the request for 1 second before doing a search rather than instant keyup. but not 100% sure how to do that...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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*/
));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...