定期发送ajax请求

Periodically send ajax requests

本文关键字:ajax 请求      更新时间:2023-09-26

有一个页面,我想定期使"后台" ajax请求。所以页面被加载,然后它应该在一定的时间内发送ajax请求。

我可能会使用cron。我以前从未使用过,所以我想知道它是否适合这项任务。还有其他更简单的方法吗?

注:时间延迟约5分钟。

由于在发送AJAX请求和接收完整响应之间存在未知的延迟,因此通常更优雅的方法是在完成前一个AJAX调用后的固定时间开始下一个AJAX调用。这样,您还可以确保您的呼叫不会重叠。

var set_delay = 5000,
    callout = function () {
        $.ajax({
            /* blah */
        })
        .done(function (response) {
            // update the page
        })
        .always(function () {
            setTimeout(callout, set_delay);
        });
    };
// initial call
callout();

Cron运行在服务器端,你正在使用HTML和AJAX,所以你应该在Javascript中解决这个问题:-)

通过使用像setInterval这样的东西,你可以继续执行一个函数,你的情况可能是像通过AJAX轮询url:

function updatePage(){
  // perform AJAX request
}
setInterval(updatePage, 5000);

根据您的rails版本,您可能能够使用periodically_call_remote,否则您将需要@Bitterzoet描述的jquery替代方案。

你可以像这样在四秒内发送ajax请求:

setInterval(get_news, 4000);
        function get_news(){
             $.ajax('/dashboards/get_news', {
                type: 'POST',
                success: function(result) {
                    if(result > 0){
                        $('#div_1').text("See "+result+" new messages");
                        $('#div_1').show();
                    }
                    else{
                        $('#div_1').css('display', 'none');
                    }
                     },
                error: function() {
                    // alert("Error")
                }
            });       
        }

你正在使用jquery吗?如果是这样,您可以实现以下方法:

// first, you need asing a callback timer
var timeout = 300; //milliseconds
// this method contain your ajax request
function ajaxRequest() { //function to ajax request
    $.ajax({
        url: "/url/to/request/"
    }).done(function(data) {
        alert("response is: " + data);
    });
}

$(document).on("ready", function(){
    //this method will be called every 300 milliseconds
    setInterval(ajaxRequest, timeout);
});