如何激发AJAX请求定期? [英] How to fire AJAX request Periodically?

查看:132
本文介绍了如何激发AJAX请求定期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

该脚本重新加载或每5秒后刷新页面。但我想用jQuery和AJAX调用来做到这一点。可能吗?

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?

推荐答案

正如其他人所指出的setInterval和setTimeout的会做的伎俩。我想强调,我从保罗爱尔兰这个出色的视频了解了一些更先进的技术:<一href="http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/">http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

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/

有关可能最终以长于重复时间间隔(如连接速度较慢的HTTP请求)的周期性任务,最好不要使用的setInterval()。如果第一个请求尚未完成,你就会开始一个又一个,你可能会在一个情况下,你必须消耗资源共享,饿死对方多次请求。您可以通过等待计划下一次请求,直到最后一个完成避免这个问题:

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

这篇关于如何激发AJAX请求定期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆