为了开始使用EventSource
API,我编写了最具学术性的示例。问题是我总是出错,我找不到任何有用的信息。当我加载home.html
时,JS 脚本在source.onerror
; 我将它打印到控制台但分析对象我找不到任何错误类型或消息,所以我不知道它出了什么问题。代码中有错误吗?可能是与服务器有关的错误?
home.html
<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();