我正在尝试使用服务器发送的事件来更新HTML文档中的特定元素。我在使用W3Schools example时更改了参数以满足我的需要。当开箱即用时,我尝试了this问题的解决方案,即在我的Content-Type标头中包含charset=utf-8
。仍然没有对HTML的更新。然后我意识到我遇到了以下错误:
EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.
这是我的.js文件中的相关JavaScript:
var source = new EventSource("warehouse.php");
source.onmessage = function(event) {
document.getElementById("processing").innerHTML += event.data + "<br>";
};
在我的PHP文件中,我具有以下内容:
if (isset($args->products)) {
orderProducts($args->products);
}
function orderProducts($products) {
$bigResponse = outgoingData(constant('bigURL'), $products[0]);
$littleResponse = outgoingData(constant('lilURL'), $products[3]);
header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-cache');
echo "data: Order has been placed.";
flush();
}
我完全陷入了困境。我想念什么?如何解决此错误?
答案 0 :(得分:1)
尝试将json编码的数据部分/元素发送回浏览器。
让我们看看我是否能正确记住...这是我无法想到的,因此未经测试!
PHP方面:
// Set SSE headers which are send along first output.
header('Content-Type: text/event-stream; charset=UTF-8');
header('Cache-Control: no-cache');
$sseId = 0; //Increment this value on each next message
$event = 'eventName'; //Name of the event which triggers same named event-handler in js.
//$data needs to be json encoded. It can be a value of any type.
$data = array ('status' => 'Progress', 'message' => 'My message or html');
//Send SSE Message to browser
echo 'id: ' . $sseId++ . PHP_EOL; //Id of message
if (!is_null($event)) {
echo 'event: ' . $event . PHP_EOL; //Event Name to trigger eventhandler
}
retry: 10000 . PHP_EOL; //Define custom reconnection time. (Default to 3s when not specified)
echo 'data: ' . json_encode($data) . PHP_EOL; //Data to send to eventhandler
//Note: When sending html, you might need to encode with flags: JSON_HEX_QUOT | JSON_HEX_TAG
echo PHP_EOL;
ob_flush();
flush();
JavaScript端:
var es = new EventSource('sse.php');
es.addEventListener('eventName', function(event) {
var returnData = JSON.parse(event.data);
var myElement = document.getElementById("processing");
switch (returnData.status) {
case 'Error':
es.close();
myElement.innerHTML = 'An error occured!';
break;
case 'Done':
es.close();
myElement.innerHTML = 'Finished!';
break;
case 'Progress':
myElement.innerHTML += returnData.message + "<br>";
break;
}
});
es.onerror = function() {
console.log("EventSource failed.");
};
在这种情况下,我仅在数据元素包含js反应的状态时使用1(命名)事件。
您还可以定义多个事件名称以用作状态,并定义相应的事件处理程序或定义在收到的每条消息上触发的处理程序。
es.onmessage = function(event) {
//This handler fires on each message received.
console.log("Incoming message.");
};
如果服务器端脚本的运行时间超过3s,请在发送的消息中指定更长的重试时间(请参阅PHP端的代码)。否则,浏览器将在3秒后重新连接,这可能会从头开始运行您的脚本并放弃上一次运行。