如何在特定的时间段内调用一个Ajax请求?
我应该使用Timer插件还是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);
,避免检查bool的需要呢? - WobblessetInterval()
。<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()
。这里有一篇很好的文章详细介绍了如何使用它们:点击这里。使用jQuery Every time Plugin。使用它,您可以在"X"时间段内进行Ajax调用。
$("#select").everyTime(1000,function(i) {
//ajax call
}
您还可以使用 setInterval 函数。
$.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);
});
})();