【发布时间】:2023-03-10 19:53:01
【问题描述】:
我正在尝试延迟 AJAX 请求,以便在输入单元格的最后一次键入后 2-3 秒发送出去。
到目前为止,我已经设法延迟了请求,但在 2-3 秒后,我收到了针对该字段中的每个 keyup 发送的一个请求...
如何让 jQuery 取消第一个键并只发送最后一个键?
这是到目前为止的代码:
$('#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 中找到了一些类似的使用 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);
}
}
【问题讨论】:
-
贴出
ajaxSearchRequest的代码 -
@Imdad 为什么有必要这样做?您已经可以看到每个按键都产生了新的超时,而无需取消之前的按键。
-
还有其他解决方法。我只能知道我是否知道函数是什么
-
有没有办法取消 .keydown 上的延迟事件?所以如果没有进一步的 keydown 事件实际上会发生?
-
@krasatos 解决方案是在设置新超时时简单地取消以前的 (
.clearTimeout) 超时。那么最后的 keyup 超时不会被取消。
标签: javascript jquery ajax delay onkeyup