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

查看:35
本文介绍了如何定期触发 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 可以解决问题.我想强调我从 Paul Irish 的这个优秀视频中学到的更高级的技术: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天全站免登陆