drl2051 2012-07-18 15:18
浏览 11
已采纳

为什么PHP会一次性发送所有内容? [重复]

Possible Duplicate:
what is output buffering?

I have some content that takes a while to be generated by PHP. Meanwhile I would like to use this simple JS trick to display a "Loading..." message. The message would disappear as soon as the output is generated.

<p id="loading_msg">Loading...</p>

<h1>Hello</h1>
<?php
    sleep(2); // This is the greedy function call
    print '<p>This content definitely took a while to be generated !.</p>';
?>

<script type="text/javascript">
    var e = document.getElementById("loading_msg");
    e.style.display = "none";
</script>

The problem is, instead of sending everything up to sleep(2); then blocking, it will wait before all the page is generated, and then, send it all at once. It obviously breaks the purpose of my "Loading..." message, because it doesn't appear before the 2 seconds have elapsed. Any ideas of why, and how I could work around this ?

  • 写回答

2条回答 默认 最新

  • dongyaxiao5884 2012-07-18 15:19
    关注

    By default, PHP will buffer your output and send a fewer number of larger chunks to the user. You can use flush to send the contents of write buffer to the user immediately:

    <p id="loading_msg">Loading...</p>
    
    <h1>Hello</h1>
    <?php
        flush();
        sleep(2);
    

    This won't work if you've previously enabled output buffering by calling ob_start or the php.ini directive output_buffering to 1.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?