PHP做进度条时,可以用 ob_flush(); flush();
两个函数来刷新缓存,将缓存中的信息发往浏览器。但要注意很多服务器会积累满4k左右的内容才发送,所以可以通过填充空格( echo str_pad('', 4096);
)来强制刷新。
public function insert($data,$html)
{
echo $html;
$i = 0;
$sum = count($data);
if($sum == 0){
echo "数据出错";
return;
}
$noped = 0;
try {
foreach($data as $v){
$tdata[] = $v;
$i++;
if( $i%20==0 || $i==$sum-1){
$ret = $this->btrManger_m->inserts100($tdata); //一次插入100条
if($ret){
$s = $i/$sum*100;
echo str_pad('', 4096); //填充缓存
echo "<script> setProgressBar(".($s).");</script>";
ob_flush();
flush();
}
else{ //出错 终止
break;
}
$tdata = array();
}
}
} catch (Exception $e) {
echo $e;
return;
}
$resultStr = "'共计".$sum."条记录,成功操作完成".$i."条!'";
echo "<script> setText(".$resultStr.");</script>";
}
前端用bootstrap的进度条实现:
function setProgressBar(width){
str=width+"%";
$('.progress-bar').attr('aria-valuenow',str).css('width',str) .html(str);
if(width == 100){
$('#idInsertResult').html("数据操作完成!");
}
}
<div class="progress">
<div class="progress-bar progress-bar-info progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="1" aria-valuemax="100" style="width: 3%;">
0%
</div>
</div>