jQuery 如何定期触发 AJAX 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5052543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:27:52  来源:igfitidea点击:

How to fire AJAX request Periodically?

jqueryajax

提问by user12345

<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?

此脚本每 5 秒重新加载或刷新页面。但我想使用 jQuery 和 AJAX 调用来做到这一点。是否可以?

回答by drewish

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/

正如其他人指出的那样, setInterval 和 setTimeout 可以解决问题。我想强调我从 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:

对于可能最终需要比重复间隔更长的周期性任务(如慢速连接上的 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);
  });
})();

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

回答by Tahbaza

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:

是的,您可以使用 JavaScriptsetTimeout()方法或setInterval()方法来调用您想要运行的代码。以下是您可以使用 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);
});

回答by Puneet

You can use setTimeoutor setInterval.

您可以使用setTimeoutsetInterval

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

不同之处在于 - setTimeout 只触发一次您的函数,然后您必须再次设置它。setInterval 不断地触发表达式,除非你告诉它停止

回答by Srihari

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,

这在指定的时间间隔内没有按预期工作,页面没有完全加载并且该函数被连续调用。最好在下面的单独函数中调用setTimeout(executeQuery, 5000);外部executeQuery()

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.

这完全按预期工作。