简体   繁体   中英

How to clear previous output and echo in php

ag.php

<?php  
ignore_user_abort(true);
set_time_limit(0);
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
$i=0;
while(1){
    echo $i;
    $i++;
    ob_flush();
    flush();

    if (connection_aborted()){
        break;
    }

    usleep(1000000);
}

ajax:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    console.log(xhttp.readyState+" "+xhttp.status);
    if (xhttp.readyState === 3 && xhttp.status ===200) {
        console.log(xhttp.responseText+"\n");

    }
};
xhttp.open("GET", "ag.php", true);
xhttp.send();

hi, at above code, i want to make a persistent connection with php and echo data in while block in 1 second interval and data comes browser like this;
0
01
012
0123
...
but i want echo data to browser like;
0
1
2
3
...
but couldn't achive it so i found this [ How to clear previously echoed items in PHP about my question but not exactly what i want i think. anybody know is there any way to empty/remove previous echoed data? is it possible? help please.

use substr()

var xhttp = new XMLHttpRequest();
var lastResponse = '';
xhttp.onreadystatechange = function() {
    //console.log(xhttp.readyState+" "+xhttp.status);
    if (xhttp.readyState === 3 && xhttp.status ===200) {

        var currentAnswer = xhttp.responseText.substr(lastResponse.length);
        lastResponse = xhttp.responseText;
        console.log(currentAnswer+"\n");

    }
};
xhttp.open("GET", "ag.php", true);
xhttp.send();

Perhaps ob_clean is what you are looking for.

void ob_clean ( void )

This function discards the contents of the output buffer. This function does not destroy the output buffer like ob_end_clean() does. The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_clean() will not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM