php实现新订单提示
PHP实现新订单提示的方法
使用AJAX轮询
在客户端使用JavaScript定时发送AJAX请求到服务器,检查是否有新订单。这种方法简单易实现,但会增加服务器负载。
// 前端JavaScript代码
function checkNewOrders() {
$.ajax({
url: 'check_orders.php',
type: 'GET',
success: function(response) {
if(response.hasNewOrder) {
showNotification('新订单到达!');
}
},
complete: function() {
setTimeout(checkNewOrders, 5000); // 每5秒检查一次
}
});
}
WebSocket实时通信
建立WebSocket连接实现真正的实时通知,适合高并发的电商系统。
// WebSocket服务器端示例
$server = new WebSocketServer('0.0.0.0', 8080);
$server->on('message', function($client, $message) use ($server) {
if($message === 'new_order') {
$server->broadcast(json_encode(['type' => 'new_order']));
}
});
数据库触发器结合推送
在订单表中创建触发器,当有新订单时触发推送通知。
CREATE TRIGGER new_order_trigger
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
INSERT INTO notifications (message) VALUES ('新订单: ' + NEW.id);
END
浏览器通知API
配合HTML5 Notification API实现桌面通知。
function showNotification(message) {
if (!("Notification" in window)) return;
if (Notification.permission === "granted") {
new Notification(message);
} else if (Notification.permission !== "denied") {
Notification.requestPermission().then(permission => {
if (permission === "granted") {
new Notification(message);
}
});
}
}
服务器推送事件(SSE)
使用Server-Sent Events技术实现单向服务器推送。
// SSE服务器端代码
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
while(true) {
$newOrders = checkDatabaseForNewOrders();
if($newOrders) {
echo "data: " . json_encode($newOrders) . "\n\n";
ob_flush();
flush();
}
sleep(1);
}
移动端推送集成
对于移动应用,可以集成Firebase Cloud Messaging或Apple Push Notification服务。
// FCM推送示例
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = [
'Authorization: key=YOUR_SERVER_KEY',
'Content-Type: application/json'
];
$data = [
'to' => '/topics/new_orders',
'notification' => [
'title' => '新订单',
'body' => '您有新订单待处理'
]
];
每种方法都有其适用场景,可以根据项目需求和服务器环境选择最合适的实现方案。实时性要求高的推荐使用WebSocket或SSE,简单项目可以使用AJAX轮询。移动端应用则需要专门的推送服务集成。







