0

我有两个看似相同的代码块。使用第一个,客户端文件(使用服务器发送事件连接)可以正确接收和显示 JSON 数据,而使用其他代码则不能。我无法为我的生活找出原因。

这是第一个工作代码

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function sendMsg($id , $msg) {
  echo "id: $id" . PHP_EOL;
  echo "data: {\n";
  echo "data: \"name\": \"Bob\", \n";
  echo "data: \"msg\": \"$msg\", \n";
  echo "data: \"id\": $id\n";
  echo "data: }\n";
  echo PHP_EOL;
  ob_flush();
  flush();
}

sendMsg(1, 'hello');

在客户端文件中,data.name 将显示“Bob”,data.msg 将显示“hello”。

是非工作代码

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$out .= "id: 1" . PHP_EOL;
$out .= "data: {\n";
$out .= "data: \"name\": \"Bob\",\n";
$out .= "data: \"msg\": \"hello\", \n";
$out .= "data: }\n";
$out .= PHP_EOL;
echo $out;
ob_flush();
flush();

对我来说似乎完全一样,但什么都不会显示!是什么赋予了?我什至尝试将非工作代码翻译为使用所有“回声”语句,而不是.out =,以便它与第一个几乎相同......有人看到错误/差异吗?

谢谢你的帮助!

4

1 回答 1

3

在您的第二个示例中,您发送的 JSON 字符串末尾有一个悬空的逗号,这是无效的。

您正在发送:

{
    "name": "Bob",
    "msg": "hello",
}                 ^---Right there
于 2013-09-06T03:14:10.480 回答