为什么PHP一次发送它? [英] Why does PHP send it all at once?
问题描述
可能存在重复:
什么是缓冲输出?
我有一些内容需要同时由PHP生成。同时我想用这个简单的JS技巧来显示加载...消息。消息一旦生成就会消失。
&的载量...< / p为H.< h1>你好< / h1>
<?php
sleep(2); //这是贪婪的函数调用
print'< p>这段内容绝对需要一段时间才能生成!。< / p>';
?>
< script type =text / javascript>
var e = document.getElementById(loading_msg);
e.style.display =none;
< / script>
问题是,不是将所有内容发送至 sleep(2);
然后阻止,它会在所有页面生成之前等待,然后然后,一次发送 。这显然打破了我的加载...消息的目的,因为它在2秒钟之前没有出现。任何想法,为什么,以及如何解决这个问题?
默认情况下,PHP将缓冲您的输出并发送更少用户数量较多的块。您可以使用 flush
立即将写入缓冲区的内容发送给用户:
< p id =loading_msg>正在加载... < / p为H.
< h1>你好< / h1>
<?php
flush();
sleep(2);
如果您之前通过调用 ob_start
或php.ini指令 output_buffering
至 1
。
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 ?
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
.
这篇关于为什么PHP一次发送它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!