试图为jQuery AJAX请求添加延迟

kra*_*tos 7 javascript ajax jquery delay onkeyup

我试图延迟一个AJAX请求,以便在输入单元的最后一个键盘后2-3秒发送它.
到目前为止,我已经设法延迟了请求,但是在2-3秒后,我收到了一个请求,为该字段中的每个密钥发送...
如何让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);
});
Run Code Online (Sandbox Code Playgroud)

上面的代码等待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);});
Run Code Online (Sandbox Code Playgroud)

这是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);
                }
        }
Run Code Online (Sandbox Code Playgroud)

Dr.*_*lle 16

将超时存储在变量中,这样您就可以清除最近的超时:

clearTimeout(window.timer);
window.timer=setTimeout(function(){ // setting the delay for each keypress
                ajaxSearchRequest($type); //runs the ajax request

        }, 3000);
Run Code Online (Sandbox Code Playgroud)

  • ffs是它的示例代码.它不需要闭合来使解决方案显而易见. (4认同)