每隔 X 分钟调用 jQuery 的 Ajax 请求。

63
如何在特定的时间段内调用一个Ajax请求? 我应该使用Timer插件还是jQuery有一个适用于此的插件?

2
你可以在谷歌上搜索这个。https://dev59.com/tm855IYBdhLWcg3wGQJM - Zabba
8个回答

146

你可以使用内置的 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

只有第二种技术有效。 - The EasyLearn Academy

13

有点晚了,但我使用了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();

为什么不在req.done内部添加setTimeout(request(),1000);,避免检查bool的需要呢? - Wobbles
很好的想法。但是bool可以用于检查请求是否在代码中的其他位置被转发。我们说只有当响应返回时才能点击提交按钮,然后您可以使用该bool来检查响应是否已经到达。 - linslusa

6
你可以在JavaScript中使用setInterval()
<script>
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall(){...}
</script>

5

无需插件。您可以仅使用jquery。

如果您想在计时器上设置一些内容,可以使用JavaScript的setTimeoutsetInterval方法:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

2
setInterval实际上来自于JavaScript而不是jQuery。 - Exploit

4
你有两个选择,你可以使用 setTimeout()setInterval()。这里有一篇很好的文章详细介绍了如何使用它们:点击这里
神奇的是它们内置于 JavaScript 中,你可以在任何库中使用它们。

2

使用jQuery Every time Plugin。使用它,您可以在"X"时间段内进行Ajax调用。

$("#select").everyTime(1000,function(i) {
//ajax call
}

您还可以使用 setInterval 函数。


链接已经失效了,那么使用它有什么好处呢?我们不能只使用setInterval吗? - Suneel Kumar

1
我发现了一个非常好的jQuery插件,可以简化这种类型的操作。你可以查看https://github.com/ocombe/jQuery-keepAlive
$.fn.keepAlive({url: 'your-route/filename', timer: 'time'},       function(response) {
        console.log(response);
      });//

0

不要使用绝对重复的计时器,应该在完成初始请求后调用函数(就像递归函数一样)。

这可以确保请求仅在完成上一个请求后发送。这避免了请求排队等问题,从而避免了拒绝服务的问题。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接