在处理过程中使用 PHP 输出缓冲发出 JavaScript
我有一些正在接收和处理大图像的 PHP 代码。我想在处理图像以使用 jQuery 更新 DOM 时在某些点回显一些 JavaScript。这是一些示例代码,但它不起作用。它只是等待整整 5 秒,然后让警报连续发生。我希望它立即发出第一个警报,然后在 5 秒后发出下一个警报。
ob_start();
echo '<script type="text/javascript">alert(\'1...\');</script>';
ob_flush();
sleep(5);
ob_start();
echo '<script type="text/javascript">alert(\'2...\');</script>';
ob_flush();
有人可以帮忙吗?
I have some PHP code that is receiving and processing large images. I'd like to echo out some JavaScript at certain points while the image is being processed to update the DOM with jQuery. Here is some sample code, but it isn't working. It just waits the entire 5 seconds and then makes the alerts happen back to back. I want it to do the first alert immediately and then next alert after 5 seconds.
ob_start();
echo '<script type="text/javascript">alert(\'1...\');</script>';
ob_flush();
sleep(5);
ob_start();
echo '<script type="text/javascript">alert(\'2...\');</script>';
ob_flush();
Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
大多数浏览器都会缓冲内容,直到达到一定的大小。尝试通过用一些东西填充脚本块来使它们更长。
另外:您应该调用 flush,而不仅仅是 ob_flush 和 确保 zlib 压缩已关闭。
Most browsers buffer content until a certain size is reached. Try making your script blocks longer by padding them with something.
Also: You should call flush, not just ob_flush, and make sure zlib compression is turned off.
这可能超出了您必须完成的范围,但我会使用 AJAX 来完成此任务。你当然可以得到你想要发生的事情,但从长远来看,这种方法并不好。
不要提交整个页面并等待它慢慢返回,而是使用 AJAX 请求上传图像并获取结果。然后客户端上的计时器可以发出单独的 AJAX“你完成了多少?”请求。这两个 PHP 实例将通过在数据库中的作业条目上设置“完成”标志等进行通信。
虽然这使客户端的内容变得更加复杂,但处理用户交互要容易得多(例如允许用户取消长时间运行的作业)并使您的 PHP 代码更加集中。
This may be out-of-scope for what you have to get done, but I'd use AJAX for this. You can certainly get what you want to occur, but the approach isn't good in the long term.
Instead of submitting the whole page and waiting for it to come back at a crawl, use an AJAX request to upload the image and get the result. Then a timer on the client can issue separate AJAX "how far done are you?" requests. The two PHP instances would communicate via setting a "done" flag on the job entry in a database, etc.
While it makes the client-side stuff a bit more complex, it is much easier to handle user interaction (such as allowing the user to cancel a long-running job) and makes your PHP code a lot more tightly-focused.
将其添加到脚本顶部将起作用:
据我所知,ob_implicit_flush(1) 会强制刷新每个输出语句。因此其他
ob_start()
和ob_flush()
调用就没有必要了。我不知道这对你是否有效。Adding this to the top of the script will work:
As far as I know,
ob_implicit_flush(1)
forces a flush on every output statement. So the otherob_start()
andob_flush()
calls wouldn't be necessary. I don't know if that works for you.以下是在 FF4 中的工作:
我很久以前就用类似的东西实现了一个聊天“服务器”。它正在工作。
这个 ob_* 的东西对此没有帮助。
Following is working in FF4:
I implemented a chat "server" with something like that long ago. It was working.
This ob_* stuff isn't helpful for this.