javascript - HTML5 服务器发送的事件

标签 javascript php html real-time server-sent-events

我正在尝试使用 SSE 构建实时应用程序。 但是,当我认为我以正确的方式编写所有内容时,它就不起作用了。 请帮我解决这个问题。 我知道 websockets 比 SSE 好,但我一开始 这是我的 index.html 代码

<!DOCTYPE html>
<html>
<head>
<title>Using SSE(Server-sent event)</title>
<meta charset="utf-8">
</head>
<body>

<h1>Getting server updates</h1>
<div id="result"></div>

<script>
if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("getdata.php");
    source.onmessage = function(event) {  
        console.log(JSON.parse(event.data));
    };
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>

这是getdata.php页面

   <?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    $pdo = new PDO("mysql:host=localhost;dbname=sse", 'root', 'secret');
    $obj = $pdo->query("select * from users");
    $arr = $obj->fetchAll();
    echo "data: ".json_encode($arr);
    flush();
   ?>

当我使用

source.onerror = function(er){
   console.log(er);   
}

我明白了

error { target: EventSource, isTrusted: true, currentTarget: EventSource, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, composed: false, timeStamp: 5152.813223, cancelBubble: false, originalTarget: EventSource }

我尝试在 html console.log(JSON.parse(event.data)); 中注释代码 但它也不起作用。

请帮助理解 SSE 的工作原理以及我的代码有什么问题?

提前致谢。

最佳答案

我发现它为什么不起作用。 我添加了\n\n

echo "data: ".json_encode($arr);

看起来像这样

echo "data: ".json.encode($arr)."\n\n";

希望对你有帮助

关于javascript - HTML5 服务器发送的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45237223/

相关文章:

javascript - Angular 2 服务本地存储

php - 如何在 Symfony 4 控制台命令中获取应用程序根路径

javascript - Jquery 事件不会在空白输入上触发

javascript - 当用户进入当前网页时,html 5 视频以全屏模式自动打开

javascript - 我们如何在给出对象适合 :contain property to the image tag? 后获得新的图像尺寸维度

php - MySQL JOIN 语句帮助

php - 每 2 项不同的 html 类

html - 图片溢出div建议

html - 在 Android 上独立于 Web 中打开推送通知

javascript - 使用 Angular ng-swipe-left 和 ng-swipe-right 在滑动过程中旋转图像