我正在尝试设置一个 HTML5 服务器发送事件,以使用 JSON 数据更新网页。 我在网上查了很多信息网站和教程,但似乎没有任何内容是为初学者(比如我)编写的。
我也在这个 StackExchange 上检查了类似问题的答案,但仍然无法解决这个问题。
我只能从“w3schools”中获得一个基本示例来工作,尽管它不使用 JSON。
我希望有人能告诉我如何让 HTML5 服务器发送事件处理 JSON 数据。
我得到的文件如下:
HTML
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
PHP
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
我想与 SSE 一起使用的 JSON 数据类型的示例如下:
{"employees":[
{
"firstName":"John",
"lastName":"Smith",
"age":"25"
},
{
"firstName":"Sally",
"lastName":"Simpson",
"age":"24"
},
{
"firstName":"Pete",
"lastName":"Daltry",
"age":"30"
}
]}
我使用以下脚本在 jQuery 和上面的 JSON 文件方面取得了一些成功:
<body>
<p id="team"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/
jquery.min.js">
</script>
<script>
$(document).ready(function(){
$.getJSON("team.json", function(data){
$.each(data, function(){
$.each(this, function(key, value){
$("#team").append(
"First Name: " + value.firstName + "<br>" +
"Last Name: " + value.lastName + "<br>" +
"Age: " + value.age + "<br><br>"
);
});
});
});
});
</script>
</body>
但是,我无法让 SSE 处理 JSON 数据。
如有任何帮助,我们将不胜感激。
最佳答案
由于来自服务器的数据是字符串格式,您可以从服务器发送一个 json 字符串。代码将是(服务器端代码)。
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$data = array(
'firstName'=>'Test',
'lastName'=>'Last'
);
$str = json_encode($data);
echo "data: {$str}\n\n";
flush();
在客户端。
var source = new EventSource("events.php");
source.onmessage = function(event) {
var jdata = JSON.parse(event.data);
console.log(jdata);
};
关于php - 带有 JSON 和 PHP 的 HTML5 服务器发送事件 (SSE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35955555/