wil*_*fun 18 javascript ajax jquery
我有一个搜索输入,在输入时将数据从输入发送到php文件.php文件在我的数据库上搜索并显示搜索选项列表.你知道,ajax风格直播搜索.
我的问题是,如果你输入的东西非常快,它可能只是从前1或2个字母开始搜索,即使已经输入了另外10个字母.这会导致一些问题.
我的jQuery看起来有点像这样:
$(document).ready(function(){
$('#searchMe').keyup(function(){
lookup(this.value);
});
});
Run Code Online (Sandbox Code Playgroud)
和
function lookup(searchinput) {
if(searchinput.length == 0) {
// Hide the suggestion box.
$("#suggestions").hide();
} else {
$('#loading').fadeIn();
$.post("/RPCsearch.php", {queryString: ""+searchinput+""}, function(data){
if(data.length > 0) {
$("#suggestions").html(data).show();
$('#loading').fadeOut();
}
});
}
} // lookup
Run Code Online (Sandbox Code Playgroud)
所以我只是很好奇,我怎么能这样做,以便我的脚本等到我在完成输入之后再运行该函数?我的逻辑说的是,如果一个键没有被按下200微秒,运行该功能,否则稍微抬起一点.
这是怎么做到的?
Jos*_*ola 52
容易,使用setTimeout.当然你只需要一次定时器,所以clearTimeout在函数开头使用它很重要...
$(function() {
var timer;
$("#searchMe").keyup(function() {
clearTimeout(timer);
var ms = 200; // milliseconds
var val = this.value;
timer = setTimeout(function() {
lookup(val);
}, ms);
});
});
Run Code Online (Sandbox Code Playgroud)
您可能对我的bindDelayedjQuery迷你插件感兴趣。它:
使用原始问题的答案bindDelayed如下所示:
// Wait 200ms before sending a request,
// avoiding, cancelling, or ignoring previous requests
$('#searchMe').bindDelayed('keyup',200,'/RPCsearch.php',function(){
// Construct the data to send with the search each time
return {queryString:this.value};
},function(html){
// Use the response, secure in the knowledge that this is the right response
$("#suggestions").html(html).show();
},'html','post');
Run Code Online (Sandbox Code Playgroud)
万一我的网站关闭了,这是Stack Overflow后代的插件代码:
(function($){
// Instructions: http://phrogz.net/jquery-bind-delayed-get
// Copyright: Gavin Kistner, !@phrogz.net
// License: http://phrogz.net/js/_ReuseLicense.txt
$.fn.bindDelayed = function(event,delay,url,dataCallback,callback,dataType,action){
var xhr, timer, ct=0;
return this.on(event,function(){
clearTimeout(timer);
if (xhr) xhr.abort();
timer = setTimeout(function(){
var id = ++ct;
xhr = $.ajax({
type:action||'get',
url:url,
data:dataCallback && dataCallback(),
dataType:dataType||'json',
success:function(data){
xhr = null;
if (id==ct) callback.call(this,data);
}
});
},delay);
});
};
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19526 次 |
| 最近记录: |