我有一个脚本可以触发 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>
在线.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$data["total"]="hello";
echo json_encode($data);
ob_flush();
flush();
?>
您需要以 EventStream 格式发送它,在本例中只需在其前面添加data:
echo 'data: ' . json_encode($data) . "\n\n";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)