PHP-JQuery实现Progress长时间运行请求


PHP - JQuery implement Progress long running request

我有一个Zend Framework应用程序,可以从IMAP帐户获取邮件。这可能需要一段时间。所以我想在前端显示还有多少邮件需要处理。

我正在考虑这个解决方案:

  • 处理邮件的对象是将处理后的邮件量(int)写入文件/db
  • 脚本运行时,每隔20秒请求一次该文件的内容,并向用户显示数字

php/javascript有更好的解决方案吗?

您可以使用flush()在某些点向浏览器输出数据。诚然,这不是一个漂亮的,但你可以(应该)重构:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>Progress Bar</title>
</head>
<body>
<!-- Progress bar holder -->
<div id="progress" style="width:500px;border:1px solid #ccc;"></div>
<!-- Progress information -->
<div id="information" style="width"></div>
<?php
// Total processes
$total = 10;
// Loop through process
for($i=1; $i<=$total; $i++){
    // Calculate the percentation
    $percent = intval($i/$total * 100)."%";
    // Javascript for updating the progress bar and information
    echo '<script language="javascript">
    document.getElementById("progress").innerHTML="<div style='"width:'.$percent.';background-color:#ddd;'">&nbsp;</div>";
    document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
    </script>';
    // This is for the buffer achieve the minimum size in order to flush data
    echo str_repeat(' ',1024*64);
    // Send output to browser immediately
    flush();
    // Sleep one second so we can see the delay
    sleep(1);
}
// Tell user that the process is completed
echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';
?>
</body>
</html>

编辑:代码示例来自W3Shaman