javascript 尝试向 jQuery AJAX 请求添加延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11308404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:42:29  来源:igfitidea点击:

Trying to add delay to jQuery AJAX request

javascriptjqueryajaxdelayonkeyup

提问by krasatos

I am trying to delay an AJAX request so that it is sent out 2-3 seconds after the LAST keyup of an input cell.
So far I have managed to delay the requests, but after 2-3 seconds I get one request sent for every keyup in the field...
How can I make jQuery cancel the first ones and just send the last keyup?
Here's the code so far:

我正在尝试延迟 AJAX 请求,以便它在输入单元格的最后一个键输入后 2-3 秒发送出去。
到目前为止,我已经设法延迟了请求,但是在 2-3 秒后,我收到了为该字段中的每个 keyup 发送的一个请求...
如何让 jQuery 取消第一个 keyup 并只发送最后一个 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);
});

This code above, waits 1 sec then sends 4-5 AJAX requests depending on keypresses. I just want one sent after the last keyup
I have found some similar solutions in StackOverflow that use Javascript, but I have not been able to implement them to my project due to my small knowledge of programming.

上面的代码等待 1 秒,然后根据按键发送 4-5 个 AJAX 请求。我只想要在最后一次发送后发送keyup
我在 StackOverflow 中找到了一些使用 Javascript 的类似解决方案,但由于我的编程知识很少,我无法将它们实施到我的项目中。

[SOLVED] Final working code, thanks to @Dr.Molle:

[已解决] 最终工作代码,感谢@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);});

Here's the ajaxSearchRequestcode:

这是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);
                }
        }

回答by Dr.Molle

store the timeout in a variable, so you will be able to clear recent timeouts:

将超时存储在一个变量中,因此您将能够清除最近的超时:

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

        }, 3000);

回答by p3drosola

What you are trying to do is called debouncing.

您尝试执行的操作称为去抖动

Here's a jquery pluginby Ben Alman that does the job.

这是Ben Alman的一个jquery 插件,可以完成这项工作。

And underscore.jsincludes this functionality as well.

underscore.js包括此功能为好。

There's really no need to hack the ajax request system. Just make sure it's called at the right moment.

真的没有必要破解 ajax 请求系统。只要确保它在正确的时间被调用。

回答by Imdad

I like the Molle's answer But I would to further improve the performance

我喜欢 Molle 的回答但我会进一步提高性能

var ajaxRequest2;  // The variable that makes Ajax possible!
function getAjaxObject()
{
                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;
                     }
                  }
                }
  return ajaxRequest2;


 }
   getAjaxObject();

    function ajaxSearchRequest($type){



               if(typeof ajaxRequest2 =="undefined" || ajaxRequest2 == false)
                {
                  return;
                }
               ajaxRequest2.abort();

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

This change will abort an on going ajax request and send a fresh request. It is helpful when you

此更改将中止正在进行的 ajax 请求并发送新请求。当你

Typed-> waited 4 sec ->request sent ->typed again (response not received) ->waited 4 second->another request fires

输入 -> 等待 4 秒 -> 请求发送 -> 再次输入(未收到响应) -> 等待 4 秒 -> 另一个请求触发