Hello I have a javascript code that listens to a PHP code via Server-Sent Events, it is working well the response is sent from the server trough a loop and when the loop ends the Server-Sent Events stops however a few seconds after the script is again listening. how can I end the Server-Sent Events when the loop from the server side ends too? Thanks.
JS :
var sse=new EventSource("data.php");
sse.onmessage=function(event){
document.getElementById("map").innerHTML+=event.data;
};
PHP:
<?php
header('Content-Type: text/event-stream'); //indicates that server is aware of server sent events
header('Cache-Control: no-cache');//disable caching of response
$coordinates = [
[
"20:11",
33.5731235,
-7.6433045
],
[
"20:11",
33.5731054,
-7.6432876
],
[
"20:11",
33.5731644,
-7.6433304
]
];
foreach($coordinates as $c){
echo "data: ".json_encode($c)."
";
ob_get_flush();
flush();
sleep(1);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…