gpt4 book ai didi

php - Jquery AJAX 实时输出?

转载 作者:搜寻专家 更新时间:2023-10-31 21:51:03 25 4
gpt4 key购买 nike

我正在尝试从 AJAX 请求中获取一些实时输出。

这是我正在使用的代码:

$.ajax({ type: "GET",   
url: "test.php?delete=students",
async: true,
success : function(data) {
console.log(data)
}
});

当我的网页上的链接触发时,会显示一个旋转的动画以表明正在发生某些事情。我还想在 div 中显示 test.php 运行时的输出。

test.php 有一个简单的循环,遍历所有学生并删除他们,然后 echo "$student removed";

当从命令行运行时,会显示删除,当通过 AJAX 运行时,我只会得到动画而不是输出。

我不确定如何获得它,我已经尝试了几个插件但都没有成功。我也尝试过使用 XMLHttpRequestresponseText 但我不确定如何正确使用它。

理想情况下,我希望每次删除都显示在 #status div 中。

任何人都可以建议如何执行此操作吗?

更新

 progress : function(data) {
console.log(data);
},

我已经添加了上面的内容并移动我在控制台中得到了一些输出。ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 44, total: 0, type: “progress”…}

扩展我可以看到包含我之后的数据的响应文本。我如何获得它以便我可以将它附加到 div

最佳答案

您可以尝试使用服务器发送的事件:https://html.spec.whatwg.org/multipage/comms.html#server-sent-events

客户端代码会很简单:

var sse = new EventSource('test.php?delete=students');
sse.addEventListener('message', function(e) {
console.log(e.data);
}, false);

在您的 test.php 中,代码将如下所示:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

for ($i = 0; $i < ob_get_level(); $i++) {//for each open buffer
ob_end_flush();//close it
}

ob_implicit_flush(1);//turn implicit flush on

//now goes what you called "loops through all students and deletes them"
while(1) {
/*here you post your code that deletes your student*/
$data = "$student removed";//message to send to client confirming deleting of particular student
echo "data: ".$data . PHP_EOL;//here you send data to client, it will receive it and handle inside 'message' event handler
echo PHP_EOL;//need this just to fulfill the SSE standard
sleep(1);//use if need to insert pause between sending new portion of data (better use it to keep your browser safe from too much of messages per second)
}

不要忘记在完成删除学生后打破你的循环=)

关于php - Jquery AJAX 实时输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42189762/

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