How to fire AJAX request Periodically?

后端 未结 4 891
执笔经年
执笔经年 2020-11-22 14:02

This script reloads or refresh the page after every 5 seconds. But I want to do it using jQuery a

4条回答
  •  天命终不由人
    2020-11-22 14:19

    I tried the below code,

        function executeQuery() {
      $.ajax({
        url: 'url/path/here',
        success: function(data) {
          // do something with the return value here if you like
        }
      });
      setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
    }
    
    $(document).ready(function() {
      // run the first time; all subsequent calls will take care of themselves
      setTimeout(executeQuery, 5000);
    });
    

    This didn't work as expected for the specified interval,the page didn't load completely and the function was been called continuously. Its better to call setTimeout(executeQuery, 5000); outside executeQuery() in a separate function as below,

    function executeQuery() {
      $.ajax({
        url: 'url/path/here',
        success: function(data) {
          // do something with the return value here if you like
        }
      });
      updateCall();
    }
    
    function updateCall(){
    setTimeout(function(){executeQuery()}, 5000);
    }
    
    $(document).ready(function() {
      executeQuery();
    });
    

    This worked exactly as intended.

提交回复
热议问题