将 PHP 响应逐字流式传输回 JS,而不保留完整历史记录

问题描述 投票:0回答:1

我想将 PHP 响应逐字流式传输到 JS,但是响应会被缓存:
PHP 文件:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
    
ob_clean();
echo "Hello ";
ob_flush();
flush();
sleep(2);

ob_clean();
echo "World ";
ob_flush();
flush();
sleep(2);

ob_clean();
echo "!";
ob_flush();
flush();
?>

JS 文件:

var httpllm = new XMLHttpRequest();
            
httpllm.onreadystatechange = function()
{
    if(httpllm.readyState == 3)
    {
        console.log(httpllm.responseText);
    }
}

httpllm.open('POST', 'test.php', true);
httpllm.send();

结果:

-> Hello
-> Hello World
-> Hello World !

我想要什么:

-> Hello
-> World
-> !

我错过了什么,只发送/接收一个单词,而不是每次回复的完整历史记录?

javascript php stream
1个回答
0
投票

我通常使用

EventSource

处理 SSE

示例:

var eventSource = new EventSource('sse.php');

eventSource.onmessage = function(event) {
    console.log(event.data);
};

这里

onmessage
单独处理每条消息!

© www.soinside.com 2019 - 2024. All rights reserved.