我们觉得在php中的一个过程中,在执行任务时显示一个进程栏,但在Chrome浏览器中,直到进程结束才显示该栏。在Chromium等其他浏览器中,它运行得很好,并显示进度条。有什么建议吗?
<!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;'"> </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>
我会成为那些问你为什么要做某事的烦人的人之一。
你真的需要将数据从服务器流式传输到浏览器吗?
除非您向用户发送大量生成的数据,否则实际上没有必要采取此类措施。
因为您没有使用WebSockets,所以您可以将有关进程的信息保存到cookie中,这样您就不必将其存储在其他任何地方,而且它与单个客户端有关,并将AJAX请求发送到一个专用页面,该页面将返回该进程的百分比或状态。
在这个过程中,你只需要用正确的值调用setcookie,比如
setcookie($name, $value, $expiration /*<--- does not matter*/);
并且在返回该值的专用页面中
return $_COOKIE[$name]; //<--- $name the same as in setcookie,
//this should probably return JSON
在js代码中,您可以(使用jquery,使其更容易)
$.get(page, function(data)
{
document.getElementById("progress").innerHTML =
'<div style="width: data;background-color:#ddd;"></div>';
}
希望这能有所帮助。