使用的是PHP的ob 函数实现
具体函数可参考 PHP官方文档Output Control 函数
前端使用了iframe具体代码如下
ob_function.php
if (ob_get_level() == 0) {
ob_start();
}
$progress = 0;
while ($progress < 100) {
$progress += rand(1, 20);
if ($progress > 100) {
$progress = 100;
}
echo "<script>parent.updateProgress({$progress});</script>";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(1);
}
ob_end_flush();
ob.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="start">开始</button>
<div id="name"></div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.js"></script>
<script>
$(function () {
$('#start').click(function () {
if ($('#my-iframe').length == 0) {
$('body').append('<iframe style="display: none" id="my-iframe" src="/ob_function.php"></iframe>');
}
});
});
function updateProgress(progress) {
$('#name').html(progress + '%');
if (progress == 100) {
$('#my-iframe').remove();
}
}
</script>
</html>
服务器如果是nginx 需要修改nginx配置文件 在http 块里面增加或修改
proxy_buffering off;
gzip off;
fastcgi_keep_conn on;