javascript - 服务器发送事件 : Not working

标签 javascript php mysql notifications server-sent-events

我正在使用 HTML5 Server-Sent Events .

实际上我需要显示通知(新记录输入和未读记录),即在数据库(php/mysql)中插入任何新记录时。

因此,出于测试目的,我只是尝试使用总行数。但是我在本地主机中收到此错误消息:

Firefox can't establish a connection to the server at http://localhost/project/folder/servevent/demo_sse.php.

行是:

var source = new EventSource("demo_sse.php");

我试过这个:

index.php

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

demo_sse.php

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

$db = mysql_connect("localhost", "root", ""); // your host, user, password
  if(!$db) { echo mysql_error(); }
$select_db = mysql_select_db("testdatase"); // database name
  if(!$select_db) { echo mysql_error(); }

$time = " SELECT count( id ) AS ct FROM `product` ";
$result = mysql_query($time);
$resa = mysql_fetch_assoc($result);
echo $resa['ct'];
flush();
?> 

请让我知道出了什么问题。

我知道通知我们可以在一定的间隔时间使用 Ajax,但我不想要这样的东西。因为我有 N 条记录,这可能会减慢我的资源。

最佳答案

根据 this ,

有几条“规则”需要满足,而你的规则在这一点上还欠缺:

  • 输出要发送的数据(总是以“data:”开头)

有点像:

echo "data: {$resa['ct']}\n\n"; 

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

相关文章:

php - 请帮我获取 $randomQ 和 $matchinA,然后在输入 $matchinA 时刷新 jQuery?

php - 简单的jquery post变量发送

php - 使用 Symfony2 同时使用两个数据库

php - 插入。 while循环,mysql

sql - 使用 graphviz 显示 SQL 脚本

mysql - Node-mysql 过时连接

javascript - 表格列中的excelJS wrapText

javascript - 如何使用jsp从数据库中检索数据

javascript - 使用另一个输入动态添加和删除输入

PHP:如何将 3D 数组转换为 mysql 结果对象?