javascript - 可以在脚本执行时使用 Ajax post 调用的 php 脚本发回 SSE 事件吗
问题描述
我的服务器上有一个执行多项任务(设置文件夹、复制文件等)的 php 脚本,我用 ajax 调用该脚本。
IE
注册.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 个会话?
解决方案
你不能这样设置,AJAX 请求会在服务器端产生一个新的 PHP 进程,它不知道第一个进程。
长时间工作的脚本应该将状态存储到数据库中,从那里可以通过第二个(,第三个,...)请求独立查询。
推荐阅读
- javascript - 使用挂钩根据变量值更新状态对象?
- python - 调用子方法时如何强制执行父方法调用?
- jquery - Extjs 4.1.0 组合框侦听从 ajax 调用完全加载的先前组合框值
- r - 在点 p1 周围创建几个点,到该点具有指定的距离。算法错误
- c# - 寻找一种更有效的方式在 startup.cs 和控制器中添加我的存储库
- deep-learning - ValueError: 层序贯_3 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:(无,180)
- docker - docker compose 中的主机和端口转发
- reactjs - 覆盖 URL 加载器限制 create-react-app craco
- maven - Liquibase Maven 插件编号格式异常
- javascript - vite@2 构建中缺少组件和资产