COMET技术具体实现 结合PHP和JQUERY
2014-07-17 13:57
405 查看
具体看代码,费话不说
PHP服务端
以下是JS端
这样的话,服务器查询数据有更新才会返回AJAX请求,没有更新会直到超时(PHP默认30秒超时),这时COMET会重新连接
这样大大降低了频繁的AJAX请求,又没有降低实时性。
PHP服务端
$mem = new RTMEM(); if(!$mem->conn()) exit('no mem server'); if(!$mem->getstate()) exit('moonjksrv is not runing'); $alminfo = $mem->get('alm_info'); if(!$alminfo) exit('no alarm'); $almobj = json_decode($alminfo); if(!$almobj) exit('no json data'); $lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0; $currentmodif = $almobj->timestamp; while ($currentmodif <= $lastmodif) // check if the data file has been modified { usleep(1000000); // sleep 1 second to unload the CPU clearstatcache(); $alminfo = $mem->get('alm_info'); if(!$alminfo) exit('no alarm'); $almobj = json_decode($alminfo); if(!$almobj) exit('no json data'); $currentmodif = $almobj->timestamp; } exit(json_encode($almobj));
以下是JS端
//comet ajax//// var Comet = function(options){ this.init(options); }; Comet.prototype = { constructor: Comet, init:function(options){ this.options = { url:"", callback:function(){} } this.options = $.extend(this.options,options||{}); this.url = this.options.url; this.callback = this.options.callback; this.timestamp = 0; this.noerror = true; this.lock = true; }, connect: function(){ this.lock = false; this.ajaxLoop(); }, disconnect: function(){ this.lock = true; }, ajaxLoop: function(){ if(this.url && !this.lock){ var _this = this; $.ajax({ url:_this.url, type:'get', data:'timestamp=' + _this.timestamp, dataType:'json', cache:false, success:function(json){ _this.timestamp = json['timestamp']; _this.handleResponse(json); _this.noerror = true; }, complete:function(){ if (_this.noerror){ _this.ajaxLoop(); }else{ // if a connection problem occurs, try to reconnect each 1 seconds setTimeout(function(){_this.ajaxLoop()}, 1000); } _this.noerror = false; } }) } }, handleResponse: function(response){ this.callback(response); }, doRequest: function(request){ if(this.url && !this.lock){ $.get(this.url, { 'msg': request } ); } } } /////// var comet = new Comet({ url:'binsrv/rt_alm.php?type=getrtalm', callback:function(json){ //接收到数据的处理 if(typeof(page)!="undefined" && typeof(page.processAlmData)=="function") page.processAlmData(json); } }); comet.connect();
这样的话,服务器查询数据有更新才会返回AJAX请求,没有更新会直到超时(PHP默认30秒超时),这时COMET会重新连接
这样大大降低了频繁的AJAX请求,又没有降低实时性。
相关文章推荐
- Jquery中的AJax技术结合PHP实现无刷新验证验证码
- jQuery结合PHP+MySQL实现二级联动下拉列表[实例]
- php配合jquery实现增删操作具体实例
- jQuery结合PHP+MySQL实现二级联动下拉列表[实例]
- 使用ajax,结合jquery,php实现图片上传预览功能
- PHP结合Jquery和ajax实现瀑布流特效
- jQuery结合PHP+MySQL实现二级联动下拉列表[实例]
- PHP结合jQuery实现红蓝投票功能特效
- jquery与php结合实现AJAX长轮询(LongPoll)
- PHP结合jQuery实现红蓝投票功能特效
- JQuery和PHP结合实现动态进度条上传显示
- Tab页界面 用jQuery及Ajax技术实现(php后台)
- php配合jquery实现增删操作具体实例
- PHP结合Jquery和ajax实现瀑布流特效
- PHP结合jQuery实现的评论顶、踩功能
- php配合jquery实现增删操作具体实例
- PHP实现推技术comet
- PHP结合jQuery.autocomplete插件实现输入自动完成提示的功能
- PHP_D4_“简易聊天室 ”的具体技术实现
- PHP结合jQuery插件ajaxFileUpload实现异步上传文件实例