如何根据在 HTML5 中使用服务器发送的事件检索的数据显示通知


How to display notification based on the data retrieved using Server-Sent Events in HTML5

我是HTML5的初学者。现在,我尝试使用 HTML5 服务器发送的事件显示表中的行数。我能够获取行数并将其显示在div 标签中。

爪哇语

<script>
            var evtSource = new EventSource("messages.php");
            console.log("Inside 1");
            console.log(evtSource);
            evtSource.onmessage = function(e) {
            var no_of_messages=e.data;
            if(no_of_messages > 0)
                {
               $("#Messages").html(e.data);
                }
                else
                    {
               $("#Messages").html(e.data);
                }  

我使用 PHP 脚本从表中获取行。

.PHP

<?php 
date_default_timezone_set("America/New_York");
header("Content-Type: text/event-stream'n'n");
$counter = rand(1, 10);
while (1) {
  // Every second, sent a "ping" event.
  echo "event: ping'n";
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT count(*) FROM messages';
mysql_select_db('apartment');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
    $message_count=$row['count(*)'];
}
mysql_close($conn);
  echo 'data: {"Messages": "' . $message_count . '"}';
  echo "'n'n";
  // Send a simple message at random intervals.
  $counter--;
  if (!$counter) {
    echo 'data:' . $message_count . "'n'n";
    error_log($message_count);
    $counter = rand(1, 10);
  }
  ob_flush();
  flush();
  sleep(1);
}?>

现在,我想在 HTML 页面中将其显示为通知,以便用户可以在弹出时看到它。

我做了什么——

<div style="height: 70px; width:100%;border-style: solid;
        border-bottom-width:1px;border-color: #ccc" id="dashboard">    
        <div id="Messages"><button id="button" type="button">Number of Messages</button></div>        
        </div>      

使用上面的 HTML 我可以显示消息数,但我想 -
1.当消息数高于0时更改按钮的颜色,并且按钮的颜色应从初始颜色红色更改为绿色。
2.是否可以使用此创建类似气球的通知。

要更改颜色,您可以使用

if (no_of_messages > 0){
    document.getElementById("button").style.background-color="red";
} else {
    document.getElementById("button").style.background-color="green";
}

但我不太确定"气球状"是什么意思,如果您可以解释更多,我会更新我的答案。