我将此脚本写入我的实时搜索:
$(document).ready(function(){
$('input#search').keypress(function(){
$('ul#pacientes_hint').html("");
var texto = $('input#search').val();
if(texto.length > 2){
$('ul#pacientes_hint').html("");
$.post("../index.php/buscar/busca2", { "texto" : texto},
function(data){
$('ul#pacientes_hint').html("");
var html_final = "";
$.each(data, function(key, value) {
html_final = html_final + value.msg;
});
$('ul#pacientes_hint').html(html_final);
}, "json");
}else{
$('ul#pacientes_hint').html("");
}
});
});
它工作正常,但是当我键入太快时它会查询,我怎么能这样做,所以一次只运行一个脚本(最后一个按键)?
答案 0 :(得分:0)
我认为你需要在完成之前杀死之前的AJAX请求。试试这个:
$(document).ready(function(){
var xhr;//Declare a global variable
$('input#search').keypress(function(){
$('ul#pacientes_hint').html("");
var texto = $('input#search').val();
if(texto.length > 2){
xhr.abort();//Add this line
$('ul#pacientes_hint').html("");
//store AJAX object in variable
xhr = $.post("../index.php/buscar/busca2", { "texto" : texto},
function(data){
$('ul#pacientes_hint').html("");
var html_final = "";
$.each(data, function(key, value) {
html_final = html_final + value.msg;
});
$('ul#pacientes_hint').html(html_final);
}, "json");
}else{
$('ul#pacientes_hint').html("");
}
});
});
答案 1 :(得分:0)
你可能最好使用Ben Alman的Throttle / Debounce:
http://benalman.com/projects/jquery-throttle-debounce-plugin/