定期发送不同的 ajax 调用

Send different ajax calls at regular intervals

本文关键字:ajax 调用      更新时间:2023-09-26

我正在努力通过图表可视化数据。我想每 X 秒发送一个不同的 ajax 调用。例如,第一个 ajax 调用将是说第一个.php x 秒后调用将是第二个.php。我怎样才能通过jQuery引入这个概念?

提前感谢您的帮助。

最好保留要在数组中使用 AJAX 调用的文件名

["first.php", "second.php", ..]

然后使用 JavaScript setTimeout 做这样的事情

`for(page in yourArray){
  (function fire() {
    $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
    //do your work with response
    },
   complete: function() {
   // Schedule the next request when the current one's complete
   setTimeout(fire, yourXSeconds);
   }
  });
 })();
}`

好的,让我给你举个例子:

  • 假设首先.php您有:

    <?php echo 'First Response'; ?>

其次.php

 `<?php echo 'Second Response'; ?>`

服务器端脚本的输出作为参数传递给成功处理程序函数,因此您将拥有

success: function(data) { alert(data); // First Response }

success: function(data) { alert(data); // apple }

<script type="text/javascript"> function test(){ alert('return sent'); $.ajax({ type: "POST", url: "first.php", data: somedata; dataType:'text'; //or HTML, JSON, etc. success: function(response){ alert(response); } }); } </script>