jquery ajax 延迟执行,javascript – 尝试为jQuery AJAX请求添加延迟

我试图延迟一个

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值