如何在php

时间:2017-02-07 06:36:32

标签: 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();

嗨,在上面的代码中,我想在1秒的时间间隔内使用php和echo数据进行持久连接,并且数据像这样来自浏览器;
0
01
012
0123
...
但我希望回声数据像浏览器一样;
0
1
2
3
...
但是无法实现它,所以我找到了这个[How to clear previously echoed items in PHP 关于我的问题但不完全是我想要的想法。 有人知道有没有办法清空/删除以前的回音数据?可能吗?求助。

2 个答案:

答案 0 :(得分:1)

或许ob_clean正是您所寻找的。

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.

答案 1 :(得分:1)

使用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();