【问题标题】:HTML5 Server-Sent Events : empty responseHTML5 服务器发送事件:空响应
【发布时间】:2026-02-05 01:40:01
【问题描述】:

我正在使用 PHP (CodeIgniter) 编写 Web 服务。 我尝试遵循一些关于 HTML5 中服务器发送事件的基本教程。

但是,我无法运行它们中的任何一个。
正如预期的那样(每 3 秒),我收到了正确的标题,但我没有收到任何数据。
可能是 WAMP 配置问题还是 CodeIgniter 问题?


控制器方法代码:

public function sse() {
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        $time = date('r');
        echo "data: The server time is: {$time}\n\n";
        flush();
    }

视图的代码(部分):

<div id="play"> msg </div>

<script>
    var source = new EventSource("<?php echo site_url('play/sse') ?>");
    source.onmessage=function(event) {
        document.getElementById("play").innerHTML+=event.data + "<br>";
    };
</script>

HTTP 标头:

Request URL:http://localhost/index.php/play/sse
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:text/event-stream
Accept-Encoding:gzip,deflate,sdch
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Cookie: ...

【问题讨论】:

  • 根据您显示的标题,您有一个响应。你确定里面没有数据吗?
  • 在 Chrome 的“Firebug”中,我得到“此请求没有可用的响应数据。”并且从未实际调用过 onmessage 函数。我是否错过了什么,事实上我可以接收数据吗?
  • @mechu,我也有同样的问题。 onmessage 没有被触发并且数据总是空的,即使当我手动输入文件时,它也不是。我不知道发生了什么......(PS:Też z Polski)

标签: php javascript codeigniter server-sent-events


【解决方案1】:

我遇到了同样的问题,我通过在标题和响应/结果中用双引号替换单引号来解决它。

   header("Content-type: text/event-stream");
   header("Connection: Keep-alive");
   header("Cache-Control: no-cache");
   echo "retry:1000\n";
   $result = "data:".json_encode($result)."\n\n"; 

【讨论】:

    最近更新 更多