function send(msg){
$.ajax({
data : {'msg' : msg},
type : 'post',
url : '{:U('Live/SendMsg')}',
success : function(response){
//alert(response);;
}
})
}
$(document).ready(function(){
connect();
$("#btn").click(function(){
var msg = $('#msg').val();
send(msg);
msg.html('');
});
}) public function SendMsg(){
$filename = './Uploads/live/'.'data.json';
if ($_POST['msg']!='') {
file_put_contents($filename,$_POST['msg']);
$this->ajaxReturn($_POST,'OK',100);
die();
}else{
$this->ajaxReturn($_POST,'on',0);
die();
}
}前台展示部分: <div id="infobox" >
1.请输入推送信息,可同时执行多条信息和JavaScript指令,每行一条<br/></div> var timestamp = 0;
var url = '/live.php';
var error = false;
function connect(){
$.ajax({
data : {
'timestamp' : timestamp
},
url : url,
type : 'get',
timeout : 0,
success : function(response){
var data = eval('('+response+')');
error = false;
timestamp = data.timestamp;
if (data.msg!='')
{
$("#infobox").append(data.msg + '<br>');
};
},
error : function(){
error = true;
setTimeout(function(){ connect();}, 5000);
},
complete : function(){
if (error)
// if a connection problem occurs, try to reconnect each 5 seconds
setTimeout(function(){connect();}, 5000);
else
connect();
}
})
}
$(document).ready(function(){
connect();
})推送模块代码:<?php
$filename = './Uploads/live/'.'data.json';
// $msg = isset($_GET['msg']) ? $_GET['msg'] : '';
// 不停的循环,直到储存消息的文件被修改
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif){ // 如果数据文件已经被修改
usleep(100000); // 100ms暂停 缓解CPU压力
clearstatcache(); //清除缓存信息
$currentmodif = filemtime($filename);
}
// 返回json数组
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
//$this->ajaxReturn($response,'ok',1);
flush();
?> ThinkPHP 是一个免费开源的,快速、简单的面向对象的 轻量级PHP开发框架 ,创立于2006年初,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。并且拥有众多的原创功能和特性,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,已经成长为国内最领先和最具影响力的WEB应用开发框架,众多的典型案例确保可以稳定用于商业以及门户级的开发。