Facebook的风格AJAX搜索 [英] Facebook Style AJAX Search
问题描述
我已经创建了一个Facebook的风格AJAX搜索我的网站,您键入它会弹出结果在下面您寻找一个很好的清单。
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();
});
这里的问题是它的一点点无效的,因为用户会输入如足球一词。这将开展8对服务器的请求。什么是做到这一点的更有效的方法?理想情况下,我认为应该做一个搜索,而不是即时KEYUP前1秒钟存储的要求。但不是100%肯定该怎么做......
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...
推荐答案
你指的是被称为反跳的方法
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
所以,你的code会被重新写成
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*/
));
这篇关于Facebook的风格AJAX搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!