最近在学习Ajax异步刷新的时候么突然想到能不能这个技术做点什么事情,网上百度了一下,发现好多人用这个写在线聊天,自己也想试试。不过,做完之后发现这种方法写的聊天室,真的很耗资源,不过就当练手学习吧。
首先介绍一下Ajax,Ajax不是一种新的编程语言,而是使用现有标准的新方法。他能实现与服务器交换数据,并且能在不刷新整个网页的情况下得到数据,Ajax主要可以用在用户登录网站时的判断其用户名密码是否正确的时候
第一步,创建数据库,储存聊天信息放在chat表中。
首页:
<html> <head> <style type="text/css"> div#container{width:500px;background-color:#99bbbb;margin:0 auto;} div#header {background-color:#99bbbb;} div#content {background-color:#EEEEEE;height:200px;width:500px;float:left;} div#input {background-color:#99bbbb;height:150px;width:500px;float:left;} div#form{width: 500px; height:80px;} div#chat_content{width: 500px; height:260px;} h1 {margin-bottom:0;} h2 {margin-bottom:0;font-size:18px;} h3{margin-bottom:0;} ul {margin:0;} li {list-style:none;} </style> <script type="text/javascript"> var int=self.setInterval("loadcontent()",1) //载入该用户的聊天记录 function loadcontent() { //通过name属性得到页面元素chat var f=document.chat; //得到content的值; var content = f.content.value; //得到recieve的值 var recieve = f.recieve.value; //得到send的值 var send = f.send.value; var xmlhttp; //创建XMLHttpRequest对象 //目前部分浏览器支持XMLHttpRequest,少部分不支持的话可以选择ActiveXObject if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //建议使用onreadystatechange,虽然这样做会比较麻烦,具体用法请见w3school xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { //服务器相应请求,改变chat_content的内容 //resposeText为接收结果 document.getElementById("chat_content").innerHTML=xmlhttp.responseText; } } //创建请求,这里用get传递参数,传递了recieve_id,send_id两个参数; //参数true表示是异步传输,这里选择异步的话,上面就得使用onreadystatechange //URL为服务器上面文件的地址 xmlhttp.open("GET","http://localhost/ChatOnline/get_chat.php?send="+send+"&recieve="+recieve,true); xmlhttp.send(); } //发送内容 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","http://localhost/ChatOnline/send_chat.php",true); var f=document.chat; var content = f.content.value; var recieve = f.recieve.value; var send = f.send.value; //发送请求 //这里使用Post方法传递参数; //将要构造的参数连接起来,接收的时候:$_POST['send']; var post_str= "content="+ content+"&recieve="+recieve+"&send="+send; //使用post的时候必须在发送请求之前加上下面这句 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send(post_str); } </script> </head> <body> <?php //接收发送者,接收者的id; $recieve_id=$_GET['recieve_id']; $send_id = $_GET['send_id']; ?> <div id="container"> <div id="header"> <h3> 聊天窗口</h3> </div> <div id="chat"> <textarea name="chat_content" id="chat_content" style="width: 480px; height:250px; margin:5px;border:0;padding:0;" readonly="readonly"> </textarea> <!-- <textarea name="chat_content" id="chat_content" cols="65.3" rows="20" style=""></textarea>--> </div> <div id="form" > <form name= "chat" > <div id="input_content" > <input id = "input" type ="textarea" name="content" style="width: 480px; height:50px; margin:5px;border:0;padding:0;" > <input type = "hidden" name="send" value ="<?php echo $send_id ?>"> <input type = "hidden" name="recieve" value = "<?php echo $recieve_id?>"> <button type="button" style="float:right" onclick="sendcontent()">发送</button> </div> </form> </div> </div> </body> </html>
首页中用到两个Ajax,一个用来不断刷新信息信息显示框,每隔1毫秒刷新一次。需要说明一下传递参数时,使用get方法和post方法:get方法很快,但是只能传递比较小的数据,post可以传递很大的数据,而且不会再url中显示出来,比较安全。在使用post的时候,第一点:必须在发送请求之前使用setRequestHeader()创建Http头,然后在send中加入参数,参数的连接以及如何接受在注释中有。
处理发送的数据:
<?php $time = date('Y-m-d H:i:s',time());; $send = $_POST['send']; $send = intval($send); $recieve = $_POST['recieve']; $recieve = intval($recieve); $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` ,`send_id` ,`recieve_id` ,`time` ,`content`) VALUES (NULL , '$send', '$recieve', '$time', '$content')"; $result = mysql_query($insert); ?>
处理接收的数据
<?php $recieve_id = $_GET['recieve']; $send_id = $_GET['send']; $con = mysql_connect("localhost","",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ing", $con); mysql_query("set names 'utf8'"); $sql = "SELECT * FROM `chat` WHERE (`send_id` =".$send_id." and `recieve_id` = ".$recieve_id.") or (`recieve_id` =".$send_id." and `send_id` =".$recieve_id.");"; $result = mysql_query($sql); if(isset($result)){ while($row = mysql_fetch_array($result)) { echo "来自:$row[1] \n"; echo "$row[3] \n"; echo "$row[4] \n"; } } else { echo "聊天记录为空"; } ?>
这部分主要的方面是sql,如何提取聊天内容能够实现一对一聊天呢?
因为数据库的信息包含发送方id,接收方id,所以我们使用这两个值来实现,比如说双方的id分别是1,2,那么只要挑选出发送方是1,并且接收方是2,或者发送方是2,并且接收方是1,就可以了。这样显示的就会是一对一的效果。
测试的时候需要注意,因为没有写登陆和注册,在Url中得填写上接收方和发送方的id
好啦,这就简单的写出来了一个一对一的在线聊天系统了!