2 回答

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
<script src="/selectedSystemState-script.js"></script>
與您的 javascript 文件名不匹配selectSystemState-script.js。下次通過(guò)打開(kāi)開(kāi)發(fā)者工具控制臺(tái)來(lái)驗(yàn)證 javascript 錯(cuò)誤!
另一個(gè)錯(cuò)誤是您在設(shè)置事件名稱(chēng)之前發(fā)送數(shù)據(jù)。結(jié)尾selectedSystemState-script.php應(yīng)該是:
echo "retry: 1000\n";
echo "event: selectedSystemStateResultsMessage\n";
echo "data: $selectedSystemStateResults" . "\n\n";
flush();

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用本教程使用服務(wù)器發(fā)送的事件
我發(fā)現(xiàn) script.php 文件不能停止執(zhí)行?。?/p>
或 (selectedSystemState-script.php) 在您的情況下。
所以我猜你鏈接的教程在某些方面是錯(cuò)誤的?
嘗試這個(gè)
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);
}
這對(duì)我來(lái)說(shuō)是新的,但我注意到了一些事情:
1- php 事件腳本文件必須有標(biāo)題 text/event-stream
2- 該文件不能停止執(zhí)行!
3-event:之前發(fā)送data:。
希望這有幫助
編輯 在對(duì)你的腳本進(jìn)行測(cè)試之后它在我改變時(shí)起作用了 <script src="/selectedSystemState-script.js"></script>
到 <script src="./selectedSystemState-script.js"></script>
它是selectedSystemState-script.js從根文件夾調(diào)用的!并產(chǎn)生 404 錯(cuò)誤
并在 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 關(guān)注
- 181 瀏覽
添加回答
舉報(bào)