How to fire AJAX request Periodically?

2018-12-31 15:40发布

问题:

<meta http-equiv=\"Refresh\" Content=\"5\">

This script reloads or refresh the page after every 5 seconds. But I want to do it using jQuery and AJAX call. Is it possible?

回答1:

As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it\'s best not to use setInterval(). If the first request hasn\'t completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:

// Use a named immediately-invoked function expression.
(function worker() {
  $.get(\'ajax/test.html\', function(data) {
    // Now that we\'ve completed the request schedule the next one.
    $(\'.result\').html(data);
    setTimeout(worker, 5000);
  });
})();

For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:

(function worker() {
  $.ajax({
    url: \'ajax/test.html\', 
    success: function(data) {
      $(\'.result\').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one\'s complete
      setTimeout(worker, 5000);
    }
  });
})();


回答2:

Yes, you could use either the JavaScript setTimeout() method or setInterval() method to invoke the code that you would like to run. Here\'s how you might do it with setTimeout:

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


回答3:

You can use setTimeout or setInterval.

The difference is - setTimeout triggers your function only once, and then you must set it again. setInterval keeps triggering expression again and again, unless you tell it to stop



标签: jquery ajax