gpt4 book ai didi

php - 以数据流的形式写入div

转载 作者:可可西里 更新时间:2023-11-01 12:29:14 24 4
gpt4 key购买 nike

考虑写入 div 的 AJAX 调用:

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

result.php 中的 PHP 脚本执行一些需要时间的功能,每步大约需要 5-20 秒。我正在使用 PHP 的 flush() 函数在每个步骤开始和结束时立即将信息发送到浏览器,但是如何让 Javascript 将数据写入 #content div 进来了吗?

谢谢。

编辑:澄清一下:假设 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();

?>

如何构造 AJAX 以调用 result.php,以便在 echo 语句进入时附加到 #content div?欢迎使用/不使用 jQuery 的任何解决方案。谢谢!

最佳答案

有一种使用 iframe 的技术可以用来实现这一点。

类似于涉及框架的其他建议,但它不涉及 session 或轮询或任何内容,并且不需要您显示 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>

Javascript,在您的主页中:

function updateProgress(progress) {
$("#progress").append("<div>" + progress + "</div>");
}

结果.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();

?>

关于php - 以数据流的形式写入div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13250976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com