每秒执行一次Ajax请求[重复]

时间:2022-12-01 10:55:12

This question already has an answer here:

这个问题在这里已有答案:

I have an ajax call being made to a php file. I am receiving results. Now I am investigating if it is possible to have the ajax request automatically perform every 1 second. I am posting the results into input field called hidden. How can I execute the ajax call every three seconds without having to call the function?

我对一个php文件进行了ajax调用。我收到了结果。现在我正在调查是否可以让ajax请求每1秒自动执行一次。我将结果发布到名为hidden的输入字段中。如何在不必调用函数的情况下每三秒执行一次ajax调用?

    $.ajax({
            type: 'POST',
            url: 'increment.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (data) {
                    $('#hidden').val(data);// first set the value     

            }
    });

3 个解决方案

#1


10  

Something you might want to consider is Server Sent Events (SSE's)

你可能想要考虑的是服务器发送事件(SSE)

This is an HTML5 technology whereby Javascript will "long-poll" a server endpoint (your PHP file) to see if any changes have occurred. Long-polling is basically where JS (I'm not sure if it uses Ajax or another technology) sends a request every second to the endpoint

这是一种HTML5技术,Javascript将“长时间轮询”服务器端点(您的PHP文件)以查看是否发生了任何更改。长轮询基本上是JS(我不确定它是否使用Ajax或其他技术)每秒向端点发送请求的地方

You can try it like this:

你可以这样试试:

#/your_js
var evtSource = new EventSource("increment.php");
evtSource.onmessage = function(e) {
    $('#hidden').val(e.data);
}

To send the data, you can make an ajax call which will send the updated JSON object to the server, like you have:

要发送数据,您可以进行ajax调用,将更新的JSON对象发送到服务器,就像您:

  $(document).on("click", ".your_object", function(data) {
     $.ajax({
                type: 'POST',
                url: 'increment.php',
                data: $(this).serialize(),
                dataType: 'json'
        });
   });

This will only open an Ajax request when you perform an event, and your app will be "listening" for the response every second. As you are aware, Ajax long-polling is super resource-intensive, so it will be better to look at web-socket stuff if you want true "real-time" technology, but either way, this will be a much more efficient system than just using plain ajax for everything

这只会在您执行事件时打开Ajax请求,并且您的应用程序将每秒“监听”响应。如您所知,Ajax长轮询是超级资源密集型的,因此如果您想要真正的“实时”技术,那么查看Web套接字的东西会更好,但不管怎样,这将是一个更高效的系统而不仅仅是使用普通的ajax

A caveat here -- you'll have to change your increment.php to handle the different response types

需要注意的是 - 您必须更改increment.php以处理不同的响应类型

#2


29  

You can do this with a repeated series of setTimeout calls. (Don't use setInterval with ajax calls, you'll get chaos in no time; setInterval will fire off the next ajax call even if the previous one hasn't completed yet.)

您可以通过重复的一系列setTimeout调用来完成此操作。 (不要将setInterval与ajax调用一起使用,你很快就会出现混乱;即使前一个调用尚未完成,setInterval也会触发下一个ajax调用。)

Use setTimeout to schedule the first call, and then when it completes to schedule the next, etc.:

使用setTimeout来安排第一个调用,然后在完成调度下一个调用时,等等:

var interval = 1000;  // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
    $.ajax({
            type: 'POST',
            url: 'increment.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (data) {
                    $('#hidden').val(data);// first set the value     
            },
            complete: function (data) {
                    // Schedule the next
                    setTimeout(doAjax, interval);
            }
    });
}
setTimeout(doAjax, interval);

Note that I'm using complete, not success, to schedule the next call, so that an interruption (temporary drop in your 'net connection, whatever) doesn't kill the process.

请注意,我使用完整而非成功来安排下一个调用,以便中断(暂时丢弃'网络连接,无论如何)不会导致进程中断。

#3


5  

Yes possible using setInterval

是的,可以使用setInterval

1) Keep your ajax within a function.

1)将ajax保留在函数中。

function fun() {
$.ajax({
            type: 'POST',
            url: 'increment.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (data) {
                    $('#hidden').val(data);// first set the value     

            }
    });
}

2) Now using setInterval, you can execute it every second.

2)现在使用setInterval,您可以每秒执行一次。

var interval = setInterval(fun, 1000);

3) To pause/clear use clearInterval

3)暂停/清除使用clearInterval

clearInterval(interval);

4) As other pointed that using setInterval for ajax is not wise, so try using

4)正如其他人指出的那样,对于ajax使用setInterval并不明智,所以请尝试使用

var interval;
function callAjax() {
  $.ajax({
                type: 'POST',
                url: 'increment.php',
                data: $(this).serialize(),
                dataType: 'json',
                success: function (data) {
                        $('#hidden').val(data);// first set the value 
                        interval = setTimeout(callAjax, 1000);   
                }
        });
}
callAjax();
//clearTimeout(interval);

#1


10  

Something you might want to consider is Server Sent Events (SSE's)

你可能想要考虑的是服务器发送事件(SSE)

This is an HTML5 technology whereby Javascript will "long-poll" a server endpoint (your PHP file) to see if any changes have occurred. Long-polling is basically where JS (I'm not sure if it uses Ajax or another technology) sends a request every second to the endpoint

这是一种HTML5技术,Javascript将“长时间轮询”服务器端点(您的PHP文件)以查看是否发生了任何更改。长轮询基本上是JS(我不确定它是否使用Ajax或其他技术)每秒向端点发送请求的地方

You can try it like this:

你可以这样试试:

#/your_js
var evtSource = new EventSource("increment.php");
evtSource.onmessage = function(e) {
    $('#hidden').val(e.data);
}

To send the data, you can make an ajax call which will send the updated JSON object to the server, like you have:

要发送数据,您可以进行ajax调用,将更新的JSON对象发送到服务器,就像您:

  $(document).on("click", ".your_object", function(data) {
     $.ajax({
                type: 'POST',
                url: 'increment.php',
                data: $(this).serialize(),
                dataType: 'json'
        });
   });

This will only open an Ajax request when you perform an event, and your app will be "listening" for the response every second. As you are aware, Ajax long-polling is super resource-intensive, so it will be better to look at web-socket stuff if you want true "real-time" technology, but either way, this will be a much more efficient system than just using plain ajax for everything

这只会在您执行事件时打开Ajax请求,并且您的应用程序将每秒“监听”响应。如您所知,Ajax长轮询是超级资源密集型的,因此如果您想要真正的“实时”技术,那么查看Web套接字的东西会更好,但不管怎样,这将是一个更高效的系统而不仅仅是使用普通的ajax

A caveat here -- you'll have to change your increment.php to handle the different response types

需要注意的是 - 您必须更改increment.php以处理不同的响应类型

#2


29  

You can do this with a repeated series of setTimeout calls. (Don't use setInterval with ajax calls, you'll get chaos in no time; setInterval will fire off the next ajax call even if the previous one hasn't completed yet.)

您可以通过重复的一系列setTimeout调用来完成此操作。 (不要将setInterval与ajax调用一起使用,你很快就会出现混乱;即使前一个调用尚未完成,setInterval也会触发下一个ajax调用。)

Use setTimeout to schedule the first call, and then when it completes to schedule the next, etc.:

使用setTimeout来安排第一个调用,然后在完成调度下一个调用时,等等:

var interval = 1000;  // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
    $.ajax({
            type: 'POST',
            url: 'increment.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (data) {
                    $('#hidden').val(data);// first set the value     
            },
            complete: function (data) {
                    // Schedule the next
                    setTimeout(doAjax, interval);
            }
    });
}
setTimeout(doAjax, interval);

Note that I'm using complete, not success, to schedule the next call, so that an interruption (temporary drop in your 'net connection, whatever) doesn't kill the process.

请注意,我使用完整而非成功来安排下一个调用,以便中断(暂时丢弃'网络连接,无论如何)不会导致进程中断。

#3


5  

Yes possible using setInterval

是的,可以使用setInterval

1) Keep your ajax within a function.

1)将ajax保留在函数中。

function fun() {
$.ajax({
            type: 'POST',
            url: 'increment.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (data) {
                    $('#hidden').val(data);// first set the value     

            }
    });
}

2) Now using setInterval, you can execute it every second.

2)现在使用setInterval,您可以每秒执行一次。

var interval = setInterval(fun, 1000);

3) To pause/clear use clearInterval

3)暂停/清除使用clearInterval

clearInterval(interval);

4) As other pointed that using setInterval for ajax is not wise, so try using

4)正如其他人指出的那样,对于ajax使用setInterval并不明智,所以请尝试使用

var interval;
function callAjax() {
  $.ajax({
                type: 'POST',
                url: 'increment.php',
                data: $(this).serialize(),
                dataType: 'json',
                success: function (data) {
                        $('#hidden').val(data);// first set the value 
                        interval = setTimeout(callAjax, 1000);   
                }
        });
}
callAjax();
//clearTimeout(interval);