我正在尝试延迟一个AJAX请求,使其在输入单元格的最后一个keyup之后2-3秒发送。
到目前为止,我已经成功地延迟了这些请求,但是在2-3秒后,每个字段的keyup都会发送一个请求...
我该如何让jQuery取消前面的请求,只发送最后一个keyup呢?
以下是到目前为止的代码:
$('#lastname').focus(function(){
$('.terms :input').val(""); //clears other search fields
}).keyup(function(){
caps(this); //another function that capitalizes the field
$type = $(this).attr("id"); // just passing the type of desired search to the php file
setTimeout(function(){ // setting the delay for each keypress
ajaxSearchRequest($type); //runs the ajax request
}, 1000);
});
上述代码将等待1秒钟,然后根据按键发送4-5个AJAX请求。
我只想在最后一个 keyup
后发送一个请求。
我在StackOverflow中找到了一些类似的解决方案,但由于我的编程知识有限,我无法将它们实现到我的项目中。
[已解决] 最终工作代码,感谢 @Dr.Molle:
$('#lastname').focus(function(){
$('.terms :input').val("");
}).keyup(function(){
caps(this);
$type = $(this).attr("id");
window.timer=setTimeout(function(){ // setting the delay for each keypress
ajaxSearchRequest($type); //runs the ajax request
}, 3000);
}).keydown(function(){clearTimeout(window.timer);});
这是 ajaxSearchRequest
的代码:
function ajaxSearchRequest($type){
var ajaxRequest2; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest2 = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest2 = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest2 = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Browser error!");
return false;
}
}
}
ajaxRequest2.onreadystatechange = function(){
if(ajaxRequest2.readyState == 4){
$result = ajaxRequest2.responseText;
$('#resultcontainer').html($result);
}}
var searchterm = document.getElementById($type).value;
var queryString ="?searchterm=" + searchterm +"&type=" +$type;
if(searchterm !== ""){
ajaxRequest2.open("GET", "searchrequest.php" +
queryString, true);
ajaxRequest2.send(null);
}
}
ajaxSearchRequest
代码。 - Imdad.clearTimeout
)的超时。然后,最后一个 keyup 超时就不会被取消。 - Esailija