使用简单的 PHP 进行 Web 通知图标





3.00/5 (3投票s)
具有颜色和通过 Ajax 实时更新的动态通知图标。
引言
在 Web 开发环境(动态网站)中,我们关注后端和发生的事件,并且需要使用动态方式通知用户,而无需打扰他,甚至不需要强迫他刷新页面来获取最新的事件。 在本文中,我将告诉您如何创建一个动态通知铃铛,以动态地通知您在浏览网页时发生的事件。
背景
最近,我开发了一个机器人应用程序 (RemoRobo),前端使用 HTML,后端使用 PHP,用于控制 Arduino 和 RaspberryPi。我需要一些技术来更新浏览器的事件,包括事件的来源、级别等,我将这部分从项目中分离出来,使其对世界有用,因此您可以在您的项目中使用它。
Using the Code
源代码像往常一样分为两个主要部分,前端和后端。
后端
在后端,我们有以下操作
- 数据库结构
- 从数据库获取事件
- 准备要显示的事件
- 取消事件
1. 数据库结构
我使用了 MySql 数据库,因为它免费,并且大多数 PHP 应用程序都使用它,但是您可以使用任何您喜欢的数据库引擎。 这是数据库通知表结构的示例
通知表具有以下列
名称 | 类型 | 描述 |
id | int | (主键) 它用于获取事件和通知到前端 |
主题 | 文本 | (必须) 用一两个词来描述事件或通知 |
来源 | int | (可选) 您可以通过数字识别事件或通知来源,例如 1= USER , 2- 服务器 3- 硬件,...等。 |
详细说明 | 字符串 | (可选) 关于事件的单行详细信息。 |
date | 时间 /日期 | (必须) 事件发生的时间,它用于过滤和排序要首先显示的事件。 |
dismiss (取消) | tinyInt (微型整型) | (必须) 这是一个标志(0 和 1),(零) 该事件未被查看,这意味着它将出现在通知列表和铃铛标签中的数字中。 (一) 表示该事件已被用户查看并取消,因此它仅保存在数据库中以备将来使用,但它将不再出现在通知列表中。 |
信号强度 | tinyInt (微型整型) | (必须) 这是事件的级别,1 = 关键,2= 警告,3 = 信息。 如果您喜欢,可以添加更多,但您也应该添加代码来为其着色。 此外,我们将其用作可选的排序因子,这意味着您可以根据发生时间或级别值对通知进行排序。 |
2. 从数据库获取事件
要从数据库获取数据,我们应该使用以下 PHP 代码
A. 连接
//PHP code
< ?php
$servername = "localhost";
$username = "root";
$password = " ";
$dbname="remorobodb";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
?>
B. 提取数据
$select_query = "SELECT * FROM `notification` WHERE `dismiss` = 0
_ORDER BY `notification`.`date` DESC";
$result = mysqli_query($conn, $select_query);
3. 准备要显示的事件
A. 转换为数组
现在,我们将重新组织返回的数据以显示在屏幕上,通过将其添加到数组中,我们有两个数组
arrayItem
: 此数组包含 Item 值,例如:ID,主题,并将其转换为有用的名称resultArray
: 此数组包含组织后的所有结果 Item。
示例
$resultCount = count($result);
for ($i=0;$i < $resultCount ;$i++)
{
//$arrayItem["index"]=$i; // FOR Indexing result
$arrayItem["notification_id"] = $result[$i][0];
$arrayItem["notification_subject"] = $result[$i][1];
$arrayItem["notification_source"] = $result[$i][2];
$arrayItem["notification_text"] = $result[$i][3];
$arrayItem["notification_date"] = $result[$i][4];
$arrayItem["notification_dismiss"] = $result[$i][5];
$arrayItem["notification_level"] = $result[$i][6];
$arrayItem["fulldetails"] = $result[$i][7];
$resultArray[$i] = $arrayItem; // Add the current result item to the total result array.
}
B. 准备打印
此源代码准备
- 最终级别:这是找到的最终最大级别,用于按该颜色对铃铛着色,(灰色、橙色、红色,...)
- 未取消的通知总数。
- 通知数组:每个通知数据的所有信息,如详细信息、主题、时间等。
提示:附件和 gitHub 中的代码格式更好。
$output = '';
$finalLevel=-2;
//////////// Rendering the lresult //////////////////
//$resultCount = count($resultArray);
if ($resultCount >0)
{
$finalLevel= $resultArray[0]["notification_level"];
for($i=0;$i< $resultCount;$i++)
{
if ($resultArray[$i]["notification_level"] < $finalLevel)
{
$finalLevel = $resultArray[$i]["notification_level"];
}
$bgColor = getBGColor( $resultArray[$i]["notification_level"]);
$resultArray[$i]["bgColor"] = $bgColor;
$output .= '
< li>
< a href="#" onclick="showModal('.$resultArray[$i]["notification_id"].',
'.$i.',\''.$resultArray[$i]["notification_subject"].'\',\'Hi there \')")>
< div style="background :'.$bgColor.';" >
< strong >'.$resultArray[$i]["notification_subject"].'</strong>
</div>
<small><em>'.$resultArray[$i]["notification_text"].'</em></small>
</a>
</li>
';
}
}
else{
$output .= '
< li>< a href="#" class="text-bold text-italic">No Noti Found</a></li>';
}
$bgColor= getBGColor($finalLevel);
$data = array(
'bellColor'=>$bgColor,
'unseen_notification' => $resultCount,
'notification' => $output,
'result'=>$resultArray
);
///////////////////Display the Result///////////////
echo json_encode($data);
function getBGColor($level)
{
$bgColor = '';
switch($level)
{
case 1:
$bgColor="red";
break;
case 2:
$bgColor="orange";
break;
case 3:
$bgColor="gray";
break;
}
return $bgColor;
}
4. 取消事件
取消通知是将取消字段从 0 转换为 1 的操作。
此源代码
- 获取 ID 用于要取消的通知。
- 所有参数(可选)您可以发送 (
ALL
) 作为参数,这意味着将一次取消所有通知。
$id =$_GET[id];
//echo $id;
if ($id=='All')
{
dismiss();
}
else
{
dismiss(' where id = '.$id);
}
function dismiss($options)
{
$sql = "Update `notification` SET `dismiss` = 1 ".$options;
DB_query($sql);
echo ($sql." Excecuted");
//echo "done";
}
前端
以下代码用于在上下文菜单中加载未查看的事件,以及总数、铃铛颜色。 使用 Ajax。
///////Global Variables
var data; // notification Data json
var currentNotificationIndex; //current notification message
var currentNotificationId; //Current Notification Id
function load_unseen_notification(view = '')
{
var serverFile = "./remoroboinclude/ajax/notification.php?id="+view;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.ontimeout= load_unseen_notificationTimeOut;
xmlhttp.onerror = load_unseen_notificationError;
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
data = JSON.parse(this.responseText);
if(data.unseen_notification > 0)
{
document.getElementById("dropdown-menu").innerHTML = data.notification;
document.getElementById("count").innerHTML = data.unseen_notification;
document.getElementById("bellIcon").style.color = data.bellColor;
document.getElementById("count").style.color = data.bellColor;
//addLog("notification Updated");
}
else
{
document.getElementById("dropdown-menu").innerHTML =
"< li>< strong>Welcome </ strong><br /><small>
< em>No new Notification ... </ em></ small></ li> ";
document.getElementById("count").innerHTML="";
document.getElementById("bellIcon").style.color = "transparent" ;
}
}//for onreadystatechange Function on success
} //for onreadystatechange Event state change
xmlhttp.open("GET",serverFile,true);
xmlhttp.send(null);
}
// Events Handellings ...
function load_unseen_notificationTimeOut()
{
alert("The request for unseen Messages timed out.");
}
function load_unseen_notificationError(){
alert("Error");
}
</script>
用于查看详细信息的 PHP 代码已在准备打印中编写,除了函数:显示模态框,我们将在其中显示
showModal
:使用 HTML 的 JavaScript,用于在引导程序模态框中显示通知详细信息
< div class="modal fade" id="divmessageModel" role="dialog">
< div class="modal-dialog">
<!-- Modal content-->
< div class="modal-content">
< div class="modal-header" id="divmessageheadercontainer">
< button type="button" class="close"
data-dismiss="modal">×</button>
< h4 class="modal-title" id="divmodalheader">Modal Header</h4>
< / div>
< div id ="divmodalmessageid" style=" visibility: hidden;"></div>
< div class="modal-body" id ="divmodalbody">
< p>Some text in the modal.</p>
< /div>
< div class="modal-footer">
<!--<div class="checkbox"> -->
< label>< input type="checkbox" value="ALL"
id="divmssagesDismissAllCheckBox" value="">
Dismiss All</label>
<!-- </div> -->
< button type="button" class="btn btn-default"
onclick="dismiss(currentNotificationId)">Dismiss</button>
< button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
< /div>
< /div>
< /div>
< /div><!-- end message Modal-->
<!--Modal JS-->
< ! -- script -- >///////////////// Script
function showModal(id='',index='',title="Hello title",
body= " this is the body ")
{
var fullTitle='';
var fullBody='';
if (id>0 && id != null)
{
//fullTitle +=id;
}
fullTitle +=title;
document.getElementById("divmssagesDismissAllCheckBox").checked = false;
document.getElementById("divmodalheader").innerHTML=fullTitle;
/*
$arrayItem["notification_id"] = $result[$i][0];
$arrayItem["notification_subject"] = $result[$i][1];
$arrayItem["notification_source"] = $result[$i][2];
$arrayItem["notification_text"] = $result[$i][3];
$arrayItem["notification_date"] = $result[$i][4];
$arrayItem["notification_dismiss"] = $result[$i][5];
$arrayItem["notification_level"] = $result[$i][6];
$arrayItem["fulldetails"] = $result[$i][7];
*/
fullBody +="<label> Full details :</label>"+ "" + "<br/>";
fullBody +="<label>Source:</label>"+
data.result[index]["notification_source"] + "<br/>";
fullBody +="<label>message:</label>"+
data.result[index]["notification_text"] + "<br/>";
fullBody +="<label>details:</label>"+
data.result[index]["fulldetails"] + "<br/>";
fullBody +="<label>date:</label>"+
data.result[index]["notification_date"] + "<br/>";
fullBody +="<label>id:</label>"+
data.result[index]["notification_id"] + "<br/>";
document.getElementById("divmessageheadercontainer").style.backgroundColor =
data.result[index]["bgColor"];
document.getElementById("divmodalbody").innerHTML= fullBody;
currentNotificationIndex = index;
currentNotificationId = id;
$('#divmessageModel').modal("show");
}
function dismiss (id='')
{
$('#divmessageModel').modal("hide");
var dismissServerFile = "./remoroboinclude/db/dismiss.php?id=";
if (id!= null)
{
if (id==''|| document.getElementById
("divmssagesDismissAllCheckBox").checked == true)
{
addLog("dismiss All Notifications");
dismissServerFile+="All";
document.getElementById("count").innerHTML ="";
}
else{
addLog("Dismiss with Id "+id);
dismissServerFile+=id;
document.getElementById("count").innerHTML ="..";
//load_unseen_notification();
}
RunPhp(dismissServerFile,'','','','notification');
} // for id != null
}
< ! -- end modal js-->
RunPhp
RunPhp
函数是通用的 Ajax 函数,我在这篇文章中写了关于它的内容:简单的动态 JavaScript Ajax 函数
历史
可以在 gitHub 上找到更新和最新版本的代码。