或者,您可以从使用另一个 php 自定义的文件中读取数据
http://..../command_receiver.php?command=blablabla
command_receiver.php
<?php
$cmd = $_GET['command'];
$fh = fopen("command.txt","w");
fwrite($fh, $cmd);
fclose($fh);
?>
demo2_sse.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//$a = $_GET["what"];
$time = microtime(true); //date('r');
$fa = fopen("command.txt", "r");
$content = fread($fa,filesize("command.txt"));
fclose($fa);
echo "data: [{$content}][{$time}]\n\n";
flush();
?>
并且 EventSource 包含在任意命名的 html 中,如下所示
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
var source = new EventSource("demo2_sse.php");
source.onmessage = function (event) {
mycommand = event.data.substring(1, event.data.indexOf("]"));
mytime = event.data.substring(event.data.lastIndexOf("[") + 1, event.data.lastIndexOf("]"));
}
</script>
</body>
</html>