javascript和JQuery焦点图和代码特效大全
当前最流行的开源CMS网站系统大全
当前位置:主页 > 编程开发 > PHP编程 >

PHP实现简单的在线聊天功能

来源:IT技术网编辑:一页书发布于:2013-08-21人围观Php实现功能简单在线聊天

PHP实现简单的在线聊天功能,具体代码如下:
相关PHP代码:
$type= $_POST['type'];
if($type=="send")
{
$msg = $_POST['msg'];
$uid = $_POST['id'];
$tuid = $_POST['tid'];
$sql = "INSERT INTO web_msg(uid,msg,tuid,status) VALUES('".$uid."','".$mysql->escape($msg)."','".$tuid."',0)";
$mysql->query($sql);
$msgid = $mysql->getLastId();
echo $msgid;
exit;
}
else if($type=="get")
{
$uid = $_POST['id'];//用户标识
$tuid = $_POST['tid'];//聊天对象标识
$msgid = $_POST['msgid'];
$sql = "SELECT * FROM web_msg WHERE STATUS=0 AND tuid='".$uid."' AND uid = '".$tuid."' ORDER BY id ASC";
$msgList = $mysql->query($sql)->rows;
$mysql->query("UPDATE web_msg SET STATUS=1 WHERE tuid='".$uid."' AND uid = '".$tuid."'");
if(empty($msgList))
{
echo "empty";exit;
}else
{
echo json_encode($msgList);
exit;
}
exit;
}
相关Javascript代码
//发送消息
function sendMsg()
{
var msg = $("#msg").val();
$("#msg").val("");
$.post("msg.php",{"type":"send","id":$("#id").val(),"tid":$("#tid").val(),"msg":msg},function(msgid){
$("#msglist ul").append('<li>me:'+msg+'</li>');
var scrollTop = $("#msglist ul").height();
        $("#msglist").scrollTop(scrollTop);
$("#msgid").val(msgid);
if(count>5)
{
clearTimeout(interval);  //关闭慢的定时器
interval = setInterval(getMsg, speedTime); 
count = 0;
}
});
}
//获取消息
function getMsg()
{
var msgid = $("#msgid").val();
$.post("msg.php",{"type":"get","id":$("#id").val(),"tid":$("#tid").val(),"msgid":msgid},function(msg){
if(msg!="empty")
{
var data = eval("("+msg+")");
for(var i=0;i<data.length;i++)
{
$("#msgid").val(parseInt(data[i].id)+1);
$("#msglist ul").append('<li>re:'+data[i].msg+'</li>');
}
var scrollTop = $("#msglist ul").height();
$("#msglist").scrollTop(scrollTop);
if(count>maxCount)
{
clearTimeout(interval);  //关闭慢的定时器
interval = setInterval(getMsg, speedTime); 
count = 0;
}
}else
{
count ++;
if(count>maxCount)
{
clearTimeout(interval);  //关闭快速定时器
interval = setInterval(getMsg, slowTime); //创建一个新的定时器
}
}
});
}
//设置时间
var speedTime = 1000;
var slowTime = 20000;
//设置次数
var count = 0;
var maxCount = 10;
//创建一个定时器
var interval;
$(function(){
$("#send").click(function(){
sendMsg();
});
$("#clear").click(function(){
$("#msglist ul").html("");
});
 
interval = setInterval(getMsg, speedTime); 
//clearTimeout(interval);  //关闭定时器  
});


Php,实现,功能,相关的文章
有时间的话来看看IT界的突发事件