PHP循环期间清除缓冲区

时间:2018-01-14 16:47:55

标签: php xmlhttprequest

的test.html

<html>
<head>
    <title>Ajax Streaming Test</title>
</head>
<body>
<center><a href="#" id="test">Test Ajax Streaming</a></center>
<script type="text/javascript">
    document.getElementById('test').onclick = function () {
        xhr = new XMLHttpRequest();
        xhr.open("GET", "test1.php", true);
        xhr.onprogress = function (e) {
            console.log(e.currentTarget.responseText);
        }
        //xhr.onreadystatechange = function () {
        //    if (xhr.readyState == 4) {
        //        console.log("Complete = " + xhr.responseText);
        //    }
        //}
        xhr.send();
    };
</script>
</body>
</html>

test1.php

for ($i = 1; $i <= 3; $i++):
    sleep(1);
    echo "$i\n";
    ob_flush();
    flush();
endfor;

点击 test.html 页面中的链接后,控制台会显示以下结果:

  • 1

  • 1
    2

  • 1
    2
    3个

在echo $i之前清除缓冲区以获得如下结果的方法是什么:

  • 1
  • 2
  • 3

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用ob_clean();它将清除整个输出缓冲区:

for ($i = 1; $i <= 3; $i++):
    sleep(1);
    ob_clean();
    echo "$i\n";
    ob_flush();
    flush();

endfor;