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 文件不能停止執行?。?/p>
或 (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 關注
- 183 瀏覽
添加回答
舉報