PHP实现消息推送
我们做web的时候偶尔会遇到消息推送,如图示例(红框位置)
当我们遇到这种功能要如何开发呢?下边将我了解的两种方法整理一下:
一、ajax轮询,定时去请求服务器数据
通过观察thinkphp官网貌似也是用的这个方法,下边将这种方法整理一下:
Notify.php
//获取通知消息
public function getNotifyCount()
{
$msg = db('message_logs')->where('isscan',0)->count();
RestfulTools::restData($msg); //这里是封装好的json_encode方法
}
notify.js
消息 {$msgCount} //这是是通过tp的 assign方法分配过来的变量,作为初始值
var getting = {
url:"{:url('Notify/getNotifyCount')}",
dataType:'json',
success:function(res) {
console.log(res);
var msgCount = res.result;
$("#msgCount").html(msgCount); //用js的 html方法去改变id为msgCount的值
}
};
//Ajax定时访问服务端,这里是3分钟请求一次。
window.setInterval(function(){
$.ajax(getting)
},180000);
二.websocket实时消息推送
这里还没测试,测试完即将完善