ajax jsp實現聊天室

來源:互聯網
上載者:User
 

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>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.