Trying to add delay to jQuery AJAX request

后端 未结 3 1789
余生分开走
余生分开走 2021-02-06 08:28

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 sec

3条回答
  •  野性不改
    2021-02-06 09:10

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

    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

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

提交回复
热议问题