php 如何只输出最后生成的那个值??

下面这段 PHP 代码:

$count = 1;

while ($count < 30)
    {
        print_r($count++ . "\r\n");
        ob_flush();
        flush();
        usleep(200 * 1000);
    }

运行结果如下:

clipboard.png

每次都会输出前面打印的和后面生成的。

然后,这边我需要ajax发送请求,实时反馈数据:

    function test(){
        G.ajax({
            url: 'prac.php' ,
            method: 'post' , 
            isAsync: true , 
            progress: function(){
                console.log('下载文件数据中:' , this.responseText);
            } , 

            load: function(){
                console.log('载入完成');
            }
        });
    }

    test();

结果是这样的:

clipboard.png

js progress 事件中,我不需要获取所有的数据,我只要每次 php sleep 输出的那一个值。

实现下面这种效果:

clipboard.png

PHP 怎么实现后面的输出覆盖掉源输出实现上面的效果??

阅读 3.7k
6 个回答

弄个变量。。。 跳出循环后输出

这不就行了么?

$count = 1;

while ($count < 30)
    {
        $count++;
        ob_flush();
        flush();
        usleep(200 * 1000);
    }
print_r($count . "\r\n");

加个判断不就好了。如下你试试看

$count = 1;

while ($count < 30){
  $c = $count++;
  if($c+1 == 30)
    print_r($count++ . "\r\n");
  ob_flush();
  flush();
  usleep(200 * 1000);
}
// 这样也行
while ($count < 30){
  $c = $count++;
  if($c+1 == 30)
    echo $c;
}
//或者这样
while ($count < 30){
  $c = $count++;
}
echo $c

你如果是要弄那种页面的数字 1=》2=》3=》4 这样跳的话用js来写

设置个头就行了, 服务器推技术就是这样的:

目测只有firefox浏览器支持, 其他的浏览器只能显示个方框

<?php 

header('Content-type:multipart/x-mixed-replace;boundary=dingjiefu');
echo "--dingjiefu\r\n";

foreach (range(1, 10) as $item) {
    echo "Content-type:text/plain\r\n\r\n";
    sleep(1);
    echo $item;
    echo "--dingjiefu\r\n";
    ob_flush();
    flush();
}

这个显示进度不是这样实现的,不是通过多次服务端的返回获取的,服务端也不会在一次请求里多次返回。

几乎全靠客户端:

https://coderwall.com/p/je3uw...

之前的答案




$count = 1;

while ($count < 30)
    {
        ob_clean();
        print_r($count++ . "\r\n");
        //这句话可以不要,我注释掉了
        //usleep(200 * 1000);
    }
    

相关阅读:

Output Control Functions

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题