Bootstrap

触发 ajax,如何定期触发Ajax请求?

fea476ab9bd534bab6d77f66ab752e0b.png

慕村225694

正如其他人所指出的,setInterval和setTimeout将起作用。我想强调一下我从保罗·爱尔兰的这段精彩视频中学到的更先进的技巧:http:/paulirish.com/2010/10对于可能花费的时间超过重复间隔的周期性任务(如慢速连接上的HTTP请求),最好不要使用setInterval()..如果第一个请求尚未完成,并且启动了另一个请求,则可能会出现多个请求消耗共享资源、彼此饥饿的情况。您可以通过等待安排下一个请求直到最后一个请求完成,来避免此问题:// 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);

  });})();为了简单起见,我使用了成功回调来调度。缺点是一个失败的请求将停止更新。为了避免这种情况,您可以使用完整的回调:(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);

    }

  });})();

;