写入div作为数据流

dot*_*hen 8 php ajax jquery

考虑写入div的AJAX调用:

recent_req=$.post('result.php', { d: data }, function(returnData) {
    $('#content').html(returnData);
});
Run Code Online (Sandbox Code Playgroud)

PHP脚本result.php执行一些需要花费时间的功能,每步约5-20秒.我正在使用PHP的flush()函数在每个步骤开始和结束时立即将信息提供给浏览器,但是如何让Javascript将数据写入#contentdiv?

谢谢.

编辑: 澄清:假设result.php看起来如下,由于约束不能实际重构:

<?php

echo "Starting...<br />";
flush();

longOperation();
echo "Done with first long operation.<br />";
flush();

anotherLongOperation();
echo "Done with another long operation.<br />";
flush();

?>
Run Code Online (Sandbox Code Playgroud)

AJAX如何构造成调用result.php,以便在#content它们进入时将echo语句附加到div?有/无jQuery的任何解决方案都是受欢迎的.谢谢!

Jed*_*son 5

有一种技术可以使用iframe来实现这一目标.

与涉及框架的其他建议类似,但它不涉及会话或轮询或任何其他内容,并且不需要您显示iframe本身.它还具有在流程中的任何一点运行您想要的任何代码的好处,以防您使用UI进行更复杂的操作,而不仅仅是将文本推送到div(例如,您可以更新进度条).

基本上,将表单提交到隐藏的iFrame,然后将javascript刷新到该帧,该帧与iFrame的父级中的函数进行交互.

像这样:

HTML:

<form target="results" action="result.php" method="post">
<!-- your form -->
<input type="submit" value="Go" />
</form>

<iframe name="results" id="results" width="0" height="0" />
<div id="progress"></div>
Run Code Online (Sandbox Code Playgroud)

Javascript,在您的主页中:

function updateProgress(progress) {
  $("#progress").append("<div>" + progress + "</div>");
}
Run Code Online (Sandbox Code Playgroud)

result.php:

<?php

echo "<script language='javascript'>parent.updateProgress('Starting...');</script>";
flush();

longOperation();
echo "<script language='javascript'>parent.updateProgress('Done with first long operation.');</script>";
flush();

anotherLongOperation();
echo "<script language='javascript'>parent.updateProgress('Done with another long operation.');</script>";
flush();

?>
Run Code Online (Sandbox Code Playgroud)