【问题标题】:How to clear previous output and echo in php如何在php中清除以前的输出和回显
【发布时间】:2017-06-24 07:23:33
【问题描述】:

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 建立持久连接并在 while 块中回显数据,并且数据像这样来自浏览器;
0
01
012
0123
...
但我想向浏览器回显数据;
0
1
2
3
...
但无法实现,所以我找到了这个 [How to clear previously echoed items in PHP 关于我的问题,但不完全是我想要的。 有人知道有什么方法可以清空/删除以前的回显数据吗?可能吗?请帮忙。

【问题讨论】:

  • 是否使用了div?
  • 在console.log中查看
  • 你的 PHP 代码做你想做的事(除了 ob_flush() 失败,因为 ob_start() 没有被调用)。似乎保留完整响应数据的是 Javascript 代码,这并不奇怪。也许在每次读取后将其重置为空字符串(或 null)可能会起作用。
  • 当您使用异步 HTTP 请求作为管道(您的服务器永远不会关闭连接)时,您可能需要管理一个本地缓冲区(在您的客户端脚本中)。

标签: php


【解决方案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();

【讨论】:

    【解决方案2】:

    也许ob_clean 就是你要找的。​​p>

    void ob_clean ( void )
    

    此函数丢弃输出缓冲区的内容。 这个函数不会像ob_end_clean() 那样破坏输出缓冲区。 输出缓冲区必须由带有PHP_OUTPUT_HANDLER_CLEANABLE 标志的ob_start() 启动。否则ob_clean() 不会 工作。

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 2011-01-12
      • 2018-11-02
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 2022-12-02
      相关资源
      最近更新 更多