如何使用HTML5 SSE发送json_encode数据

kam*_*808 6 javascript php html5 json

我有一个脚本,它触发一个SSE事件,用于从online.php获取json编码数据.在谷歌搜索,我找到了通过引入换行符来发送带有sse的JSON数据的方法.

我正在寻找的是当使用PHP的json_encode()函数创建JSON数组时如何通过SSE发送JSON.

我写了以下几行代码,但是有人可以帮助我在哪里添加SSE所需的"数据:\n \n"吗?

<script>
if(typeof(EventSource)!=="undefined")
{
  var source=new EventSource("online.php");
  source.onmessage=function(event)
  {
     var data=JSON.parse(event.data);
     $("#new_message").html("Inbox"+data['total']);
  };    
}
else
{
  $("#new_message").html("HTML5 not supported");
}
</script>
Run Code Online (Sandbox Code Playgroud)

online.php

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$data["total"]="hello";
echo json_encode($data);
ob_flush();
flush(); 
?>
Run Code Online (Sandbox Code Playgroud)

Rya*_*Cue 11

您需要以EventStream格式发送它,在这种情况下,它只是在它前面 data:

echo 'data: ' . json_encode($data) . "\n\n";
Run Code Online (Sandbox Code Playgroud)


Phi*_*l_t 5

您可以$data像Ryan所说的那样对数组进行编码:

echo 'data: ' . json_encode($data) . "\n\n";
Run Code Online (Sandbox Code Playgroud)

然后,客户端event.data将被视为一个字符串,然后您可以使用查询轻松解析为json jQuery.parseJSON().所以你的客户端代码看起来像这样:

// Check if the browser supports SSE
if (typeof (EventSource) !== "undefined") {

              var source = new EventSource("script.php");
              // Handle evetns
              source.onmessage = function(event) {
                  // parse the data that has an object as a string
                  var msg = $.parseJSON(event.data);
                     // Do awesome code with the values inside msg
              };
        } else {
              alert("Sorry, your browser doesn't support this awesome feature!");
        }
Run Code Online (Sandbox Code Playgroud)

资料来源:http://api.jquery.com/jquery.parsejson/