【发布时间】:2011-06-23 06:14:07
【问题描述】:
如何在特定时间段内调用 Ajax 请求? 我应该使用 Timer Plugin 还是 jQuery 有这个插件?
【问题讨论】:
如何在特定时间段内调用 Ajax 请求? 我应该使用 Timer Plugin 还是 jQuery 有这个插件?
【问题讨论】:
您可以使用内置的 javascript setInterval。
var ajax_call = function() {
//your jQuery ajax code
};
var interval = 1000 * 60 * X; // where X is your every X minutes
setInterval(ajax_call, interval);
或者如果你是更简洁的类型......
setInterval(function() {
//your jQuery ajax code
}, 1000 * 60 * X); // where X is your every X minutes
【讨论】:
有点晚了,但我使用了 jQuery ajax 方法。但是如果我没有从上一个请求中得到响应,我不想每秒都发送一个请求,所以我这样做了。
function request(){
if(response == true){
// This makes it unable to send a new request
// unless you get response from last request
response = false;
var req = $.ajax({
type:"post",
url:"request-handler.php",
data:{data:"Hello World"}
});
req.done(function(){
console.log("Request successful!");
// This makes it able to send new request on the next interval
response = true;
});
}
setTimeout(request(),1000);
}
request();
【讨论】:
setTimeout(request(),1000); 并避免检查布尔值?
你可以在javascript中使用setInterval()
<script>
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall(){...}
</script>
【讨论】:
不需要插件。您只能使用 jquery。
如果你想在计时器上设置一些东西,你可以使用 JavaScript 的 setTimeout 或 setInterval 方法:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
【讨论】:
你有几个选择,你可以setTimeout() 或setInterval()。 Here's a great article that elaborates on how to use them.
神奇之处在于它们内置于 JavaScript,您可以将它们与任何库一起使用。
【讨论】:
使用 jquery Every time Plugin 。使用它你可以在“X”时间段内进行 ajax 调用
$("#select").everyTime(1000,function(i) {
//ajax call
}
您也可以使用 setInterval
【讨论】:
我发现了一个非常好的 jquery 插件,可以通过这种类型的操作来减轻你的生活。您可以结帐https://github.com/ocombe/jQuery-keepAlive。
$.fn.keepAlive({url: 'your-route/filename', timer: 'time'}, function(response) {
console.log(response);
});//
【讨论】:
您应该在完成初始请求后调用该函数(如递归函数),而不是使用绝对重复计时器。
这可确保仅在完成前一个请求后才发送请求。这样可以避免请求排队等问题,从而避免拒绝服务。
(function ajaxRequest() {
$.ajax('url_of_your_application.php', {
type: 'post',
data: {
phone: '1234567890',
},
})
.done(function (data) {
// Do whatever you want with the data.
})
.always(function (data) {
// We are starting a new timer only AFTER COMPLETING the previous request.
setTimeout(ajaxRequest, 5000);
});
})();
【讨论】: