Using flush() replace last line rather than make new one in php

时光怂恿深爱的人放手 提交于 2019-12-04 18:36:42

You Would need to use javascript to replace the element already on the page:

<p id="ob">1</p>
<?php
$range = range(0, 5);
foreach ($range as $times) {
    if (ob_get_level() == 0) ob_start();
    for ($i = 0; $i<1; $i++){
        echo "<script>document.getElementById('ob').innerHTML ='example$times';</script>";
        echo str_pad('',4096)."\n";
        ob_flush();
        flush();
        sleep(1.2);
    }
    ob_end_flush();
}
?>

Or a much better way would be to use AJAX to poll the server for the next value.

<?php
if(isset($_GET['poll'])){
    echo $_GET['poll']+1;
    die;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var value = 0;
function poll(){
    setTimeout(function(){
        $.ajax({ url: "./test.php?poll="+value,cache: false,
        success: function(data){
            value = data;
            $("#ob").html('example'+value);
            //Next poll
            poll();
        }});
    }, 1200);
}

$(document).ready(function(){
    poll();
});
</script>
<p id="ob">example0</p>

Assuming that you are outputting html, you should do that on the client side in javascript.

The php alternative would be to show one line and have the page reload to show the next one. Needlessly complex and a waste of resources.

Note that php cannot modify html that is already sent to the browser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!