首页 > 解决方案 > 可以在脚本执行时使用 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 个会话?

标签: javascriptphpajax

解决方案


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

长时间工作的脚本应该将状态存储到数据库中,从那里可以通过第二个(,第三个,...)请求独立查询。


推荐阅读