现在的位置: 首页 > 综合 > 正文

ajax jsp实现聊天室

2012年11月29日 ⁄ 综合 ⁄ 共 10603字 ⁄ 字号 评论关闭
 

tw-sack.js
/* Simple AJAX Code-Kit (SACK) */
/* 2005 Gregory Wild-Smith */
/* [url]www.twilightuniverse.com[/url] */
/* Software licenced under a modified X11 licence, see documentation or authors website for more details */

function sack(file){
this.AjaxFailedAlert = "Your browser does not support the enhanced functionality of this website, and therefore you will have an experience that differs from the intended one./n";
this.requestFile = file; // 提交的页面
this.method = "POST";
this.URLString = "";
this.encodeURIString = true;
this.execute = false;

this.onLoading = function() { };//读取中
this.onLoaded = function() { };//已经读取
this.onInteractive = function() { };//交互中
this.onCompletion = function() { }; // 信息返回之后执行的方法
this.complete = function(){};//处理完毕
this.createAJAX = function() {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err) {
this.xmlhttp = null;
}
}
if(!this.xmlhttp && typeof XMLHttpRequest != "undefined")
this.xmlhttp = new XMLHttpRequest();
if (!this.xmlhttp){
this.failed = true;
}
};

this.setVar = function(name, value){
if (this.URLString.length < 3){
this.URLString = name + "=" + value;
} else {
this.URLString += "&" + name + "=" + value;
}
}

this.encVar = function(name, value){
var varString = encodeURIComponent(name) + "=" + encodeURIComponent(value);
return varString;
}

this.encodeURLString = function(string){
varArray = string.split('&');
for (i = 0; i < varArray.length; i++){
urlVars = varArray[i].split('=');
if (urlVars[0].indexOf('amp;') != -1){
urlVars[0] = urlVars[0].substring(4);
}
varArray[i] = this.encVar(urlVars[0],urlVars[1]);
}
return varArray.join('&');
}

this.runResponse = function(){
eval(this.response);
}

this.runAJAX = function(urlstring){
this.responseStatus = new Array(2);
if(this.failed && this.AjaxFailedAlert){
alert(this.AjaxFailedAlert);
} else {
if (urlstring){
if (this.URLString.length){
this.URLString = this.URLString + "&" + urlstring;
} else {
this.URLString = urlstring;
}
}
if (this.encodeURIString){
var timeval = new Date().getTime();
this.URLString = this.encodeURLString(this.URLString);
this.setVar("rndval", timeval);
}
if (this.element) { this.elementObj = document.getElementById(this.element); }
if (this.xmlhttp) {
var self = this;
if (this.method == "GET") {
var totalurlstring = this.requestFile + "?" + this.URLString;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestFile, true);
}
if (this.method == "POST"){
try {
this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8')
} catch (e) {}
}

this.xmlhttp.send(this.URLString);
this.xmlhttp.onreadystatechange = function() {
switch (self.xmlhttp.readyState){
case 1: //读取中
self.onLoading();
break;
case 2: //已经读取
self.onLoaded();
break;
case 3: //交互中
self.onInteractive();
break;
case 4: //处理完毕
self.response = self.xmlhttp.responseText;
self.responseXML = self.xmlhttp.responseXML;
self.responseStatus[0] = self.xmlhttp.status;
self.responseStatus[1] = self.xmlhttp.statusText;
self.onCompletion();
if(self.execute){ self.runResponse(); }
if (self.elementObj) {
var elemNodeName = self.elementObj.nodeName;
elemNodeName.toLowerCase();
if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea"){
self.elementObj.value = self.response;
} else {
self.elementObj.innerHTML = self.response;
}
}
self.URLString = "";
self.complete();
break;
}
};
}
}
};
this.createAJAX();
}

display.js
function overInput(a){
getId("btn").style.border = "1px solid #54ce43"
getId("content").style.border = "1px solid #54ce43"
focs()
}
function outInput(a){
getId("btn").style.border = "1px solid #AAA"
getId("content").style.border = "1px solid #AAA"
focs()
}
function overBtn(a){
a.src = "images/hover.gif"
}
function outBtn(a){
a.src = "images/rest.gif"
}
function lrover(a){
a.style.backgroundColor = "#EEE"
}
function lrout(a){
a.style.backgroundColor = "#FFF"
}
function focs(){
getName("content").focus();
}
function clean(){
getName("content").value = ""
}
var chats = new Array()
var chatStart
function addChat(strChat){
if(chats.length > 199){
chats.shift()
}
chats.push(strChat)
chatStart = chats.length
}
function preChat(){
if(chatStart && chatStart >= 1){
if(chatStart == 1){
getName("content").value = chats[0]
chatStart = 0.5
}else{
chatStart -= 1
getName("content").value = chats[chatStart]
}
}
getId("loadifo").innerHTML = chatStart+","+chats.length
}
function nextChat(){
if(chatStart && chatStart < chats.length && chats.length > 1){
if(chatStart == 0.5){
chatStart = 1
}else if(chatStart == chats.length - 1){
chatStart = chats.length - 1
}else{
chatStart += 1
}
getName("content").value = chats[chatStart]
}
getId("loadifo").innerHTML = chatStart+","+chats.length
}
window.onload = function(){
getId("outs").onmousedown = function(){
overs = 1
}
getId("outs").onmouseout = function(){
overs = 0
focs()
}
getName("content").onkeydown = function(e){
if(document.all){
var Keys = event.keyCode;
}else{
var Keys = e.which;
}
//alert(Keys)
if(Keys == "38"){
preChat()
}else if(Keys == "40"){
nextChat()
}else if(event.ctrlKey && Keys == "13"){
doUsingPost()
}else if(event.ctrlKey && Keys == "46"){
clean()
}
}

}
function getId(objId){
return document.getElementById(objId)
}
function getName(objName){
return document.getElementsByName(objName)[0]
}

chat.js
var overs;
var clien = 0;
function doUsingGet(){
var ajax=new sack("chat.jsp");
ajax.setVar("clien",clien);
ajax.setVar("timeStamp",new Date().getTime());
ajax.method='GET';
ajax.onLoading=function(){
document.getElementById("zt").innerHTML="读取中......";
}
ajax.onCompletion=function(){// 信息返回之后执行的方法
CheckState(ajax.responseXML.documentElement);
}
ajax.onLoaded=function(){
document.getElementById("zt").innerHTML="已经读取......";
}
ajax.onInteractive=function(){
document.getElementById("zt").innerHTML="交互中......";
}
ajax.complete = function(){
document.getElementById("zt").innerHTML="处理完毕......";
}
ajax.runAJAX();
}
function doUsingPost(){
if(getName("content").value!=""){
var named = getName("named").value;
var content = getName("content").value;
var ajax=new sack("chat.jsp");
ajax.setVar("clien",clien);
ajax.setVar("content",content);
ajax.setVar("named",named);
ajax.setVar("timeStamp",new Date().getTime());
ajax.method='POST';
ajax.onLoading=function(){
document.getElementById("zt").innerHTML="读取中......";
}
ajax.onCompletion=function(){// 信息返回之后执行的方法
CheckState(ajax.responseXML.documentElement);
}
ajax.onLoaded=function(){
document.getElementById("zt").innerHTML="已经读取......";
}
ajax.onInteractive=function(){
document.getElementById("zt").innerHTML="交互中......";
}
ajax.complete = function(){
document.getElementById("zt").innerHTML="处理完毕......";
}
ajax.runAJAX();
focs();
clean();
}else{
alert("请输入对话内容!")
focs()
}
}

function CheckState(res){
var resLen = res.getElementsByTagName("items").length
if(getTag(res,0,"num") != clien){
clien = getTag(res,0,"num")
for(var i=0; i<resLen; i++){
var useName = getTag(res,i,"name")
var useMag = getTag(res,i,"conts")
var useIp = getTag(res,i,"ip")
if(clien != "0" && useMag != ""){
if(useName != ""){
var lis = "用户"+ useName + "说:" + useMag //+ " ["+ useIp + "]"
}else{
var lis = "用户 ["+ useIp + "] 说:" + useMag
}
}else{
var lis = ""
}
getId("chatmain").innerHTML += lis + "<br />"
}
innerSize()
}
}

function innerSize(){
if(overs != 1){
if(getId("chatmain").offsetHeight < getId("outmain").offsetHeight){
getId("chatmain").style.marginTop = getId("outmain").offsetHeight - getId("chatmain").offsetHeight +"px";
}else{
getId("chatmain").scrollIntoView(false)
}
}
}
function getTag(response,i,objTagName){
try{
var nodeV = response.getElementsByTagName(objTagName)[i].firstChild.nodeValue;
}catch(e){
var nodeV = ""
}
return nodeV;
}
setInterval("doUsingGet()",1000)

chat.jsp
<%@ page contentType="text/xml; charset=gb2312" %>
<%!
String func(String content){
return content.replaceAll("<","<").replaceAll(">",">");
}
%>
<%
String ip=request.getRemoteAddr(); //客户端IP
int clien = new Integer(request.getParameter("clien")).intValue(); //当前是第几个用户 如果为0就是新来的用户
if(application.getAttribute("counts")==null){
application.setAttribute("counts",new Integer(0));
}
int counts = new Integer(application.getAttribute("counts").toString()).intValue(); //当前用户的ID
if(request.getParameter("content")!=null){
synchronized(this){
if(counts < 21){
int i = counts + 1;
application.setAttribute("counts",new Integer(i));
}else if(counts >= 21){
application.setAttribute("counts","1");
}
counts = new Integer(application.getAttribute("counts").toString()).intValue(); //当前用户的ID
int Cnum = counts;
String names;
String Msgs = request.getParameter("content");
// Msgs=new String(Msgs.getBytes("iso8859-1"),"gb2312");
application.setAttribute("ips" + Cnum,ip) ;
application.setAttribute("msgs" + Cnum,func(Msgs)) ;
if(request.getParameterValues("content") != null){
names = request.getParameter("named");
}else{
names = "";
}
application.setAttribute("names" + Cnum,names +"") ;
}
}
%><?xml version="1.0" encoding="gb2312" ?>
<ppl>
<num><%=application.getAttribute("counts")%></num>
<%
if(clien == 0){
%>
<items>
<ip><%=ip%></ip>
</items>
<%
}else if(clien < counts){
for(int i=clien; i<counts; i++){
int s = i+1;
String useName = (String)application.getAttribute("names" + s);
String useMsg = (String)application.getAttribute("msgs" + s);
String useIp = (String)application.getAttribute("ips" + s);
%>
<items>
<aaa><%=clien%> <%=s%></aaa>
<bbb><%=counts%></bbb>
<name><%=useName%></name>
<conts><%=useMsg%></conts>
<ip><%=useIp%></ip>
</items>
<%
}
}else if(clien > counts){
for(int i=clien; i<21; i++){
String useName = (String)application.getAttribute("names" + i);
String useMsg = (String)application.getAttribute("msgs" + i);
String useIp = (String)application.getAttribute("ips" + i);
%>
<items>
<name><%=useName%></name>
<conts><%=useMsg%></conts>
<ip><%=useIp%></ip>
</items>
<%
}
for(int m=1; m<=counts; m++){
String useNameM = (String)application.getAttribute("names" + m);
String useMsgM = (String)application.getAttribute("msgs" + m);
String useIpM = (String)application.getAttribute("ips" + m);
%>
<items>
<name><%=useNameM%></name>
<conts><%=useMsgM%></conts>
<ip><%=useIpM%></ip>
</items>
<%
}
}else if(clien == counts){

}
%>
</ppl>

index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title></title>
<link href="images/chatstyle.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="js/display.js"></script>
<script type="text/javascript" src="js/chat.js"></script>
<script type="text/javascript" src="js/tw-sack.js"></script>

</head>
<body>
<div id="zt"></div>
<div id="loadifo"></div>
<div id="outs"><div id="outmain"><div id="chatmain"></div></div></div>
<div class="in">昵称:
<input class="names" name="named" type="text" />
<span id="inputput" class="inputput" onmouseover="overInput(this)" onmouseout="outInput(this)">
<input class="inputs" name="content" type="text" title="提交对话
快捷键:Enter或Ctrl + Enter
清除
快捷键:Ctrl + Delete" /><input class="left" type="button" onmouseover="lrover(this)" value=" " onmouseout="lrout(this)" onclick="preChat();" title="向前一条对话记录
快捷键:↑" />
<input class="right" onmouseover="lrover(this)" type="button" value=" " onmouseout="lrout(this)" onclick="nextChat();" title="向后一条对话记录
快捷键:↓" />
<input id="btn" class="btn" type="image" src="images/rest.gif" onmouseover="overBtn(this)" onmouseout="outBtn(this)" onclick="doUsingPost();" title="提交对话
快捷键:Enter或Ctrl + Enter" />
</span>
<span id="errors"></span>
</div>
</body>
</html>

抱歉!评论已关闭.