我试图延迟一个
AJAX请求,以便在输入单元的最后一个键盘后2-3秒发送它.
到目前为止,我已设法延迟请求,但在2-3秒后,我收到一个请求发送给该字段中的每个密钥…
如何让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请求.
我只想在最后一个密钥后发送一个
我在StackOverflow中发现了一些使用Javascript的类似解决方案,但由于我对编程知之甚少,我无法将它们实现到我的项目中.
[解决了]
最终的工作代码,感谢@ 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);
}
}