为了使用
EventSource
API,我写了一个最学术的例子。问题是我总是遇到错误,而且找不到任何有用的信息。当我加载home.html
时,JS脚本在source.onerror
处停止运行; 我将其打印到控制台中,但分析该对象时,我无法找到任何错误类型或消息,因此我不知道出了什么问题。这段代码中是否有错误?可能与服务器相关的错误吗?<body>
<div id="result"></div>
<script src="sse.js"></script>
</body>
sse.js
function isSseEnabled() {
return (typeof EventSource !== "undefined");
}
if (isSseEnabled()) {
var source = new EventSource('source.php');
source.onerror = function(e) {
console.log(e);
source.close();
};
source.onmessage = function (e) {
console.log(e.data);
document.getElementById('result').innerHTML += e.data.concat('<br>');
}
} else {
throw 'SSE not enabled';
}
source.php
<?php
header('Content-Type: text/event-stream');
header('Cache-control: no-cache');
$time = date('r');
echo "Time: $time";
flush();