本文介绍了节流一个Ajax livesearch功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想掐死以下AJAX实时搜索功能,我写的。
I would like to throttle the following ajax live search function I wrote.
余使它这样如果至少2个字符被输入请求仅发送。我也想扼杀阿贾克斯一季度的第二个让用户输入他们想要的东西的机会。我裹在setTimeout函数阿贾克斯,但没有奏效。
I made it so that requests are only sent if a minimum of 2 characters are entered. I also want to throttle the ajax for a quarter of a second to give the user a chance to type what they want. I wrapped the ajax in a setTimeout function, but that didn't work.
$('#search').keyup(function() {
var string = $(this).val();
if (string.length >= 2) {
$.ajax({
'type': 'GET',
dataType: 'html',
'url': url,
'success': function(data){
// show the search data
}
});
} else if (string.length <= 1) {
// restore page content as of when it was loaded
}
});
另外一件事我要问,我也许应该缓存AJAX的结果,不是吗?
Another thing I should ask, I should probably cache the results of the ajax, no?
推荐答案
在就在code。如果(string.length减&GT; = 2)
:
var elem = $(this);
// save newest search
elem.data('search',search)
// clear pending searches
.clearQueue().stop()
// waits
.delay(250)
// runs search
.queue(function() {
$.ajax({
'type': 'GET',
dataType: 'html',
'url': url,
'success': function(data){
// check if can be run
if(elem.data('search') != search)
return;
// show the search data
}
});
});
这篇关于节流一个Ajax livesearch功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!