ajax实现简单的多人聊天

来源:互联网 发布:长歌门捏脸数据 编辑:程序博客网 时间:2024/05/01 00:28

原理:简单来说就是利用ajax的异步,ajax每隔一段时间会从后台获取数据而不刷新页面。

步骤:1。数据库里建两张表,一张用户表,一张消息表

isGet表示消息是否被读

2.使用java web做后台,主要使用hibernate和struts2框架,xml数据格式。

3.下面给出核心jsp代码:

friend.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'firend.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript" src="my.js"></script>
 <script type="text/javascript">
 
 function change1(val,obj){
 
     if(val=='over'){
         obj.style.color='red';
         obj.style.cursor='hand';
     }
     else if(val=='out'){
         obj.style.color='black';
     }
 
 }
 
 function openChatRoom(obj){
     window.open("${pageContext.request.contextPath}/chat/friend_gotochat.action?username="+encodeURI(obj.innerText),"_blank");
 }
 
 </script>

  </head>
 
  <body>
  <h1>欢迎${user.username }</h1>
   <ul>
   <c:forEach items="${list}" var="everyuser">
   <li onmouseover="change1('over',this)" onclick="openChatRoom(this)"
   onmouseout="change1('out',this)">${everyuser.username }</li>
  
   </c:forEach>
   </ul>
  </body>
</html>

以上代码的功能只是实现当用户点击好友列表的某个好友时,浏览器打开一个新的聊天界面

 


chating.jsp:

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'chating.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript" src="my.js"></script>
   <script type="text/javascript">

//打开新窗口的大小
   window.resizeTo(700,400);

//每隔5秒向后台要数据
   window.setInterval("getMessage()",5000);

//向后台要数据的函数
   function getMessage(){
   var myXmlHttpRequest=getXmlHttpObject();
   if(myXmlHttpRequest){
   var url="${pageContext.request.contextPath}/chat/chat_backchat.action";
   var data="getterid="+'${user.id }'+"&senderid="+'${usertochat.id}';
   myXmlHttpRequest.open("post",url,true);
   myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
   myXmlHttpRequest.onreadystatechange=function (){
   if(myXmlHttpRequest.readyState==4){
   if(myXmlHttpRequest.status==200){

//当数据回来后,将数据显示在指定位置
   var meses=myXmlHttpRequest.responseXML;
   var contents=meses.getElementsByTagName("content");
   var sendtimes=meses.getElementsByTagName("sendtime");
   for(var i=0;i<contents.length;i++){
    var str='${usertochat.username }'+":"+contents[i].childNodes[0].nodeValue+"\r\n"+sendtimes[i].childNodes[0].nodeValue
    $('mycons').value+=str+"\r\n";
   }
   }
   }
   }
   myXmlHttpRequest.send(data);
   }
   }
   //发送数据的函数
   function sendmessage(){
   var myXmlHttpRequest=getXmlHttpObject();
   if(myXmlHttpRequest){
   var url="${pageContext.request.contextPath}/chat/chat_gochat.action";
   var data="con="+${'con'}.value+"&getterid="+'${usertochat.id}'+"&senderid="+'${user.id }';
   //window.alert(data);
   myXmlHttpRequest.open("post",url,true);
   myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
   myXmlHttpRequest.onreadystatechange=function (){
   if(myXmlHttpRequest.readyState==4){
   if(myXmlHttpRequest.status==200){
   }
   }
   }
   myXmlHttpRequest.send(data);
   $('mycons').value+='${user.username }'+":"+$('con').value+"\r\n"+new Date().toLocaleString()+"\r\n";
   $('con').value="";
   }
   }
   </script>
  </head>
 
  <body>
    <h1>聊天室,<font color="red">${user.username }</font>正在和<font color="red">${usertochat.username }</font>聊天</h1>
    <textarea cols="70" rows="10" id="mycons"></textarea><br/>
    <input type="text" id="con" style="width:400px"/>
    <input type="button" value="发送消息" onclick="sendmessage()"/>
  </body>
</html>

 

my.js:

 

//创建ajax
   function getXmlHttpObject(){
   var xmlHttpRequest;
   //XmlHttpObject
   if(window.ActiveXObject)
   {
   //window.alert("ie");
   xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
   }
   else{
   //window.alert("ff");
   xmlHttpRequest=new XmlHttpRequest();
   }
   return xmlHttpRequest;
   }
  
    //获取id
   function $(id){
   return document.getElementById(id);
   }
  
   //encode"+","&"(对加号和空格编码)
   function URLencode(sStr)  

 
    return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g,'%2F'); 
 

 

 

 

0 0
原创粉丝点击