我正在尝试使用 SSE 构建实时应用程序。 但是,当我认为我以正确的方式编写所有内容时,它就不起作用了。 请帮我解决这个问题。 我知道 websockets 比 SSE 好,但我一开始 这是我的 index.html 代码
<!DOCTYPE html>
<html>
<head>
<title>Using SSE(Server-sent event)</title>
<meta charset="utf-8">
</head>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("getdata.php");
source.onmessage = function(event) {
console.log(JSON.parse(event.data));
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
这是getdata.php页面
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$pdo = new PDO("mysql:host=localhost;dbname=sse", 'root', 'secret');
$obj = $pdo->query("select * from users");
$arr = $obj->fetchAll();
echo "data: ".json_encode($arr);
flush();
?>
当我使用
source.onerror = function(er){
console.log(er);
}
我明白了
error { target: EventSource, isTrusted: true, currentTarget: EventSource, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, composed: false, timeStamp: 5152.813223, cancelBubble: false, originalTarget: EventSource }
我尝试在 html console.log(JSON.parse(event.data)); 中注释代码 但它也不起作用。
请帮助理解 SSE 的工作原理以及我的代码有什么问题?
提前致谢。
最佳答案
我发现它为什么不起作用。 我添加了\n\n
echo "data: ".json_encode($arr);
看起来像这样
echo "data: ".json.encode($arr)."\n\n";
希望对你有帮助
关于javascript - HTML5 服务器发送的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45237223/