1、创建聊天消息表,其表的字段有消息内容,发送时间和发送者的名称;
sql:
create table `guanhui`.`message` ( `id` int(10) not null auto_increment comment '消息id' , `content` varchar(255) not null comment '消息内容' , `sender` varchar(60) not null comment '发送者' , `send_time` int(10) not null comment '发送时间' , primary key (`id`) ) engine = myisam;
2、创建php文件将聊天消息查询出来,并以json格式输出;
$con = mysql_connect("localhost","",""); if (!$con) { die('could not connect: ' . mysql_error()); } mysql_select_db("chat", $con); mysql_query("set names 'utf8'"); $sql = "select * from `message`"; $result = mysql_query($sql); if(isset($result)){ json_encode(array( 'code' => 0, 'msg' => 'ok', 'data' => mysql_fetch_array($result, mysql_assoc) )) } else { json_encode(array( 'code' => 0, 'msg' => '聊天信息为空!' )) }
3、在前端使用ajax轮询请求php文件,并将消息展示出来。
setinterval(function(){ $.get('/get_message_list.php', function(data){ $(data).each(function(value, item){ $('#message_list').append('来自:' + data.sender + '的消息:' + data.message + '发送时间:', data.send_time); }); }); }, 600);
4、创建send_message.php用来接收发送的消息,并将数据储存到数据库。
$send_time = date('y-m-d h:i:s',time());; $send = $_post['sender']; $content = $_post['content']; $con = mysql_connect("localhost","",""); if (!$con) { die('could not connect: ' . mysql_error()); } mysql_select_db("ing", $con); mysql_query("set names 'utf8'"); $insert="insert into `chat` (`id` ,`sender` ,`content` ,`send_time`) values (null , '$sender', '$content', '$send_time')"; $result = mysql_query($insert);
5、在前端获取要发送的消息,并请求send_message.php。
function sendcontent() { var xmlhttp; if (window.xmlhttprequest) {// code for ie7+, firefox, chrome, opera, safari xmlhttp=new xmlhttprequest(); } else {// code for ie6, ie5 xmlhttp=new activexobject("microsoft.xmlhttp"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readystate==4 && xmlhttp.status==200) // 服务端返回了正确数据,开始响应处理 { document.getelementbyid("input").innerhtml=""; } } xmlhttp.open("post","/send_message.php",true); var f=document.chat; var content = f.content.value; var sender = f.sender.value; //发送请求 //这里使用post方法传递参数; //将要构造的参数连接起来,接收的时候:$_post['send']; var post_str= "content="+ content+"&sender="+sender; //使用post的时候必须在发送请求之前加上下面这句 xmlhttp.setrequestheader("content-type","application/x-www-form-urlencoded"); xmlhttp.send(post_str); }
更多学习内容请访问:
腾讯t3-t4标准精品php架构师教程目录大全,只要你看完保证薪资上升一个台阶(持续更新)
黄山市民网:https://www.huangshanshimin.com/