gpt4 book ai didi

javascript - 使用 Ajax post 调用的 php 脚本可以在脚本执行时发回 SSE 事件吗

转载 作者:行者123 更新时间:2023-12-02 21:30:11 24 4
gpt4 key购买 nike

我的服务器上有一个 php 脚本,它执行多个任务(设置文件夹、复制文件等),我使用 ajax 调用该脚本。

signup.js:

const evtSource = new EventSource("/createuser.php", { withCredentials: true } );
evtSource.onmessage = function(event) {
console.log(event.data);
}

$.ajax({
type: 'POST',
url: '/createuser.php',
dataType: 'json',
data: {
'username': "test user",
'usertype' : "author"
},
success: function(data){
console.log("user created");
}
});

现在在 createuser.php 上我尝试向我的网页发送消息:

创建用户.php:

<?php
function SendProgressMessage($op){
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

switch($op){
case "userCreated":
echo "User Created";
break;
case "foldersCreated":
echo "Folder structure created";
break;
case "TemplatesCopied":
echo "Templates Copied";
break;
}
flush();
}
?>

我可以将 evtSource 设置为相同的脚本和 ajax 调用,还是为脚本创建 2 个 session ?

最佳答案

你不能这样设置,AJAX请求将导致服务器端产生一个新的PHP进程,而服务器端不知道第一个进程。

长期工作的脚本应将状态存储到数据库中,以便可以通过第二个(、第三个……)请求独立查询该状态。

关于javascript - 使用 Ajax post 调用的 php 脚本可以在脚本执行时发回 SSE 事件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60638528/

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