PHP Ajax:PHP算法的实时报告


PHP Ajax: live report of the PHP algorithm

如果我在文件test.php中有下一个算法:

for ($i = 0; $i < 1000; ++$i)
{
     //Operations...
     ALERT_TO_MAIN_PAGE($i);
}

我用AJAX从页面main.html调用test.php

如何使用实时值跟踪$i的进度?

因此main.html将显示为这样,每当PHP文件完成一次迭代时:

Done 0.
Done 1.
Done 2.
...

您可以尝试使用HTML5服务器发送事件向浏览器发送类似的消息。

马上离开网站:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
/**
 * Constructs the SSE data format and flushes that data to the client.
 *
 * @param string $id Timestamp/id of this connection.
 * @param string $msg Line of text that should be transmitted.
 */
function sendMsg($id, $msg) {
  echo "id: $id" . PHP_EOL;
  echo "data: $msg" . PHP_EOL;
  echo PHP_EOL;
  ob_flush();
  flush();
}
$serverTime = time();
sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));

不能这样做,因为ajax在php端等待操作完成。

您应该离线(在后台)运行php,并使用ajax简单地询问状态(即从会话中读取有关进度的信息)。