【发布时间】:2018-07-31 15:30:38
【问题描述】:
我想将数据发布到我的 PHP 页面,然后让它更新 HTML 页面。我遵循this 使用服务器发送事件将更新推送到网页的示例。 这是我现在拥有的:
输出.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="serverData"></div>
</body>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("send_sse.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
};
}
else {
document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}
</script>
</html>
send_sse.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$val = 0;
if (isset($_POST['msg'])){
$val = $_POST['msg'];
}
echo "data: $val\n\n";
ob_flush();
?>
form.html:
<html>
<body>
<form action="send_sse.php" method="post">
Message: <input type="text" name="msg"><br>
<input type="submit">
</form>
</body>
</html>
问题是当表单发布值时,它不会更新 output.html。它确实输出“0”,并且每当我手动更改 $val 的值并保存文件时都会更新。但是,我希望在 PHP 文件之外确定 $val 的值。我做错了什么?
【问题讨论】:
标签: javascript php html post server-sent-events