![](/img/trans.png)
[英]HTML5 Server-Sent Events: How to set withCredentials option?
[英]How to display notification based on the data retrieved using Server-Sent Events in HTML5
我是 HTML5 的初學者。 現在我正在嘗試使用 HTML5 Server-Sent Events 顯示表格中的行數。 我能夠獲取行數並將其顯示在 div 標簽中。
Javascript
<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";
}
但是我不太確定“像氣球一樣”是什么意思,如果您可以多解釋一點,我會更新我的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.