为什么 XmlHttpRequest 等到完成 PHP 响应 (proc_open) 即使刷新?

Why XmlHttpRequest wait until complete PHP response (proc_open) even with flush?

我正在尝试使用 xhr 执行命令 (wp cli)。 我的问题是当我用 javascript 调用我的文件 deploy.php 时。 没有 JS 调用脚本工作,刷新是立即的。

当我在 XmlHttpRequest 中调用 deploy.php 时,响应一直等到 php 执行结束。

我尝试了不同的命令(grep / wp cli / find)但结果是一样的。

我在 WSL Debian + Chrome 上工作。

// PHP
public function liveExecuteCommand($cmd, $ajax = false)
{
        ob_start();

        $descriptorspec = array(
            0 => array("pipe", "r"),
            1 => array("pipe", "w"),
            2 => array("file", "error-output.txt", "a")
        );

        $output = '';
        $process = proc_open($cmd, $descriptorspec, $pipes);

        if (is_resource($process)) {

            fwrite($pipes[0], '<?php print_r($_ENV); ?>');
            fclose($pipes[0]);

            while ($s = fread($pipes[1], 8192)) {
                $output .= $s;
                print $s;
                $this->doFlush();
            }

            fclose($pipes[1]);
            $return_value = proc_close($process);

            //echo "La commande a retourné $return_value\n";
        }
        if ($ajax == false) {
            return $output;
        }
}


$obj->liveExecuteCommand($cmd, true);
die();
// JS
function getLiveStream() {
            var ajax = new XMLHttpRequest();
            var url = 'https://www.monsite.local/deploy.php';
            ajax.open('GET', url, true);

            ajax.onprogress = function() {
                document.getElementById("xhr_cmd_result").innerHTML = ajax.responseText;
                console.log('onprogress');
            }
            ajax.onload = function() {
                console.log('onload');
            }
            ajax.onreadystatechange = function() {
                document.getElementById("xhr_cmd_result").innerHTML = ajax.responseText;
                console.log('statechange');
            }
            ajax.send();
}

window.addEventListener('DOMContentLoaded', (event_loaded) => {
            document.getElementById("xhr_cmd").onclick = getLiveStream;
});

在Google chrome控制台中,结果直接显示所有状态(1分钟后),如php结果。

statechange
onprogress
statechange
onprogress
statechange
onprogress
statechange
onload

我希望每次调用冲洗时都有一个 console.log 。 当我在浏览器中执行 php 文件时没有问题,问题肯定在 javascript.

我该如何解决这个问题?

让我用简单的话来解释你。

Javascript's XMLHttpRequest(AJAX) call will request to server. It will only waits for response from server(final output from your php page), irrespective to internal process of server.