【问题标题】:Pushing updates to a webpage using server-sent events使用服务器发送的事件将更新推送到网页
【发布时间】: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


    【解决方案1】:

    您在这里遇到的问题是您错过了 SSE 在概念上的工作方式。您的 output.html 页面正在向您的网络服务器发出 GET 请求并执行脚本 send_sse.php 并打开一个连接并HOLDING该连接打开并等待更新。

    当您从form.html 发帖时,您正在向您的网络服务器发送一个 POST 请求并在一个完全不同线程上执行脚本send_sse.php

    由于您尚未在这两个线程之间实现任何共享持久性,因此没有任何区别。

    因此,要执行您想做的事情,您需要在 send_sse.php 中拥有具有某种形式的全局持久性(例如数据库)的代码,并且可以检测新数据,然后将其刷新到浏览器。

    我不是 PHP 专家,但我在 Node JS 中编写了an example,它使用 REDIS pub/sub 来提供上述持久性。

    希望对你有帮助。

    【讨论】:

    • 这有助于我找到完整的解决方案。但是,我现在无法完全回忆起完整的解决方案是什么哈哈。不过我会接受这个作为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2018-02-17
    • 2018-11-07
    • 1970-01-01
    相关资源
    最近更新 更多