2 回答
TA贡献1809条经验 获得超8个赞
<script src="/selectedSystemState-script.js"></script>
与您的 javascript 文件名不匹配selectSystemState-script.js。下次通过打开开发者工具控制台来验证 javascript 错误!
另一个错误是您在设置事件名称之前发送数据。结尾selectedSystemState-script.php应该是:
echo "retry: 1000\n";
echo "event: selectedSystemStateResultsMessage\n";
echo "data: $selectedSystemStateResults" . "\n\n";
flush();
TA贡献1900条经验 获得超5个赞
使用本教程使用服务器发送的事件
我发现 script.php 文件不能停止执行!!
或 (selectedSystemState-script.php) 在您的情况下。
所以我猜你链接的教程在某些方面是错误的?
尝试这个
while (1) {
// Every second, send a "selectedSystemStateResultsMessage" event.
echo "event: selectedSystemStateResultsMessage\n";
require("selectedSystemStateResults.php");
$selectedSystemStateResults = json_encode($selectedSystemStateResults);
echo "data: $selectedSystemStateResults" . "\n\n";
ob_end_flush();
flush();
sleep(1);
}
这对我来说是新的,但我注意到了一些事情:
1- php 事件脚本文件必须有标题 text/event-stream
2- 该文件不能停止执行!
3-event:之前发送data:。
希望这有帮助
编辑 在对你的脚本进行测试之后它在我改变时起作用了 <script src="/selectedSystemState-script.js"></script>
到 <script src="./selectedSystemState-script.js"></script>
它是selectedSystemState-script.js从根文件夹调用的!并产生 404 错误
并在 selectedSystemState-script.php
<?php
header("Cache-Control: no-cache");
header("Content-Type: text/event-stream");
// Require the file which contains the $animals array
require_once "selectedSystemStateResults.php";
// Encode the php array in json format to include it in the response
$selectedSystemStateResults = json_encode($selectedSystemStateResults);
// data after event
flush();
echo "retry: 1000\n";
echo "event: selectedSystemStateResultsMessage\n";
echo "data: $selectedSystemStateResults" . "\n\n";
?>
我编辑selectedSystemState-script.js了一下:
let eventSource = new EventSource('selectedSystemState-script.php');
eventSource.addEventListener("selectedSystemStateResultsMessage", function(event) {
let data = JSON.parse(event.data);
let listElements = document.getElementsByTagName("li");
for (let i = 0; i < listElements.length; i++) {
let selectedSystemStateResults = listElements[i].textContent;
if (!data.includes(selectedSystemStateResults)) {
listElements[i].style.color = "red";
} else {
listElements[i].style.color = "blue";
}
}
});
- 2 回答
- 0 关注
- 164 浏览
添加回答
举报