应Aether之邀写一个基础点的AJAX操作实例,想来想去就写一个聊天室吧,以前写AJAX时一来偷懒,二来为了简单,都用纯文本或者javascript数组进行交互,这次改成纯粹的xml操作。想得时候很简单,无非就处理发送消息,接收消息,登陆和退出这几种事件,但真正要写的时候还是颇费周折,主要是ASP对Session间的消息(对象)传递功能太弱了,只能在Application、数据库、自定义服务端组件三种方法中挑一个,自定义服务端组件先Pass了,既然要写一个轻量级的,数据库能不用就不用了,最后还是盯上了Application。
聊天室最重要的功能就是一个用户发出消息后所有用户都要能接收到,接受到消息后应该给这则消息一个标记或者删除操作。ASP的Application对象可以实现Session间的数据交互,再结合类似于Map的Scripting.Dictionary这个内置对象,应该就能实现我想要的效果。但是在实际编写过程中发现Scripting.Dictionary对象实例根本无法存储到Application中,查了MSDN后才知不允许将OBJECT和自定义组件以外的对象存储到Application中,包括自定义Class,晕,只得另想办法,最后选定用数组方式解决。
客户端我用javascript的prototype(原型)功能写了一个ChatRoom类,用面向对象的方式实现了发送接收消息,登录和退出。下面就是聊天窗口,请输入昵称登录后就能开始聊天了:)程序还有很多bug,实在无心调试了。
<%@ CODEPAGE=65001 %><%
Option Explicit
'On Error Resume Next
Response.Buffer = true
Dim act
act = Request("act")
Const CHAT_SESSION = "CHAT_ROOM_AJAX_SESSION"
Const CHAT_MSG = "CHAT_ROOM_AJAX_MSG"
Const CHAT_NICKNAME = "CHAT_ROOM_AJAX_NICKNAME"
Dim SessionArray, MsgArray, i, onlineCount
If Not IsEmpty(Application(CHAT_SESSION)) Then
Application.Lock
SessionArray = Split(Application(CHAT_SESSION), ",")
MsgArray = Split(Application(CHAT_MSG), Chr(13))
Application.UnLock
Else
'Application.Lock
'Application(CHAT_SESSION) = Session.SessionID
'Application.UnLock
End If
Function FindArray(Arr, Var)
If IsEmpty(Arr) Or IsNull(Arr) Then
FindArray = -1
Exit Function
End If
If UBound(Arr) = 0 Then
FindArray = -1
Else
For i = 0 To UBound(Arr)
If Arr(i) = Var Then
FindArray = i
Exit Function
End If
Next
End If
FindArray = -1
End Function
If Request.ServerVariables("REQUEST_METHOD") = "POST"
Then
Response.Clear
Response.ContentType = "text/xml"
Dim xmlHead, xmlFoot, msg
xmlHead = "<?xml version=""1.0"" encoding=""UTF-8""
standalone=""yes"" ?><chatroom online=""" & onlineCount
& """ self=""" & Session(CHAT_NICKNAME) &
""">"
xmlFoot = "</chatroom>"
If act = "sendChat" Then
If IsNull(SessionArray) Or IsEmpty(SessionArray) Then
Response.End
msg = "<msg nick=""" & Request("nick") &""">"
& Request("msg") & "</msg>"
For i = 0 To UBound(SessionArray)
If SessionArray(i) <> Session.SessionID Then
MsgArray(i) = MsgArray(i) & Chr(10) & msg
Application.Lock
Application(CHAT_MSG) = Join(MsgArray, Chr(13))
Application.UnLock
End If
Next
Response.Write xmlHead
Response.Write "<msg nick=""" & Session(CHAT_NICKNAME)
&""">" & Request("msg") & "</msg>"
Response.Write xmlFoot
ElseIf act = "getChat" Then
Dim pos
pos = FindArray(SessionArray, Session.SessionID)
If pos > -1 Then
If IsArray(MsgArray) Then
Dim Arr
If MsgArray(pos) <> "" Then
Response.Write xmlHead
Arr = Split(MsgArray(pos), Chr(10))
If Not IsEmpty(Arr) And UBound(Arr) >= 0 Then
For i = 0 To UBound(Arr)
Response.Write Arr(i)
Next
End If
Response.Write xmlFoot
MsgArray(pos) = ""
Application.Lock
Application(CHAT_MSG) = Join(MsgArray, Chr(13))
Application.UnLock
End If
End If
End If
ElseIf act = "login" Then
If Len(Request("nick")) > 0 Then
Dim nickArr
If Not IsEmpty(Application(CHAT_NICKNAME)) Then
nickArr = Split(Application(CHAT_NICKNAME), Chr(10))
If Not IsEmpty(nickArr) Then
For i = 0 To UBound(nickArr)
If nickArr(i) = Request("nick") Then
Response.Write xmlHead
Response.Write "<login nick=""" & Session(CHAT_NICKNAME)
& """>昵称[" & Request("nick") & "]已经被其他用户选用,请更改昵称!</login>"
Response.Write xmlFoot
Response.End
End If
Next
End If
End If
If FindArray(SessionArray, Session.SessionID) = -1 Then
Application.Lock
If IsEmpty(SessionArray) Then
Application(CHAT_SESSION) = Session.SessionID
SessionArray = Split(Application(CHAT_SESSION), ",")
Application(CHAT_MSG) = ""
MsgArray = Split(Application(CHAT_MSG), Chr(13))
Application(CHAT_NICKNAME) = Request("nick")
Else
Application(CHAT_SESSION) = Join(SessionArray, ",") &
"," & Session.SessionID
SessionArray = Split(Application(CHAT_SESSION), ",")
Application(CHAT_MSG) = Join(MsgArray, Chr(13)) &
Chr(13) & ""
MsgArray = Split(Application(CHAT_MSG), Chr(13))
Application(CHAT_NICKNAME) = Application(CHAT_NICKNAME)
& Chr(10) & Request("nick")
End If
Application.UnLock
If IsNull(SessionArray) Or IsEmpty(SessionArray) Then
Response.End
For i = 0 To UBound(SessionArray)
If SessionArray(i) <> Session.SessionID Then
MsgArray(i) = MsgArray(i) & "<system>用户[" &
Request("nick") & "]进入了聊天室</system>" & Chr(10)
Application.Lock
Application(CHAT_MSG) = Join(MsgArray, Chr(13))
Application.UnLock
End If
Next
End If
Session(CHAT_NICKNAME) = Request("nick")
Response.Write xmlHead
Response.Write "<login nick=""" & Session(CHAT_NICKNAME)
& """>OK</login><system>用户[" & Session(CHAT_NICKNAME)
& "]进入了聊天室</system>"
Response.Write xmlFoot
End If
ElseIf act = "logout" Then
Dim str, str1, str2
If Not IsEmpty(Application(CHAT_NICKNAME)) Then
nickArr = Split(Application(CHAT_NICKNAME), Chr(10))
End If
For i = 0 To UBound(SessionArray)
If SessionArray(i) <> Session.SessionID Then
If i = 0 Then
str = SessionArray(i)
str1 = MsgArray(i)
str2 = nickArr(i)
Else
str = str & "," & SessionArray(i)
str1 = str1 & Chr(10) & MsgArray(i) & Chr(13)
& "<system>用户[" & request("nick") & "]退出了聊天室!</system>"
str2 = str2 & Chr(10) & nickArr(i)
End If
End If
Next
Application.Lock
Application(CHAT_SESSION) = str
Application(CHAT_MSG) = str1
Application(CHAT_NICKNAME) = str2
Application.UnLock
End If
ElseIf act = "script" Then
Response.Clear
Response.ContentType = "text/javascript"%>
//*********************************************************
// 目的: AJAX类
// 输入: 无
// 返回: 返回XMLHttp对象
// 例子: var myConn = new XHConn();
//
// if (!myConn) alert("XMLHTTP not available. Try a newer/better
browser.");
//
// var fnWhenDone = function (oXML) { alert(oXML.responseText);
};
//
// myConn.connect("mypage.php", "POST", "foo=bar&baz=qux",
fnWhenDone);
//
//*********************************************************
function XHConn()
{
var xmlhttp = false, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { alert(e);xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone,
parObj)
{
if (!xmlhttp) return false;
bComplete = false;
sVars = (sVars == '') ? Math.random() : sVars + '&'
+ Math.random( );
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL + '?' + sVars, true);
xmlhttp.setRequestHeader("Content-Type", "text/html;charset=GB2312");
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp, parObj);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
var URL, VAR;
//*****************************************************
// 聊天类
//*****************************************************
var ChatRoom = function(obj, parentWin, w, h) {
this.style = {
width : w ? w : 500, //宽
height : h ? h : 300 //高
}
this.obj = obj; //聊天类的实际DOM名称
this.parentWin = parentWin ? parentWin : null; //聊天窗口的父级DOM对象
this.input = null; //聊天信息输入框
this.chatWin = null; //聊天信息显示DOM对象
this.login = null; //昵称输入框
this.loginBtn = null; //登陆(退出)按钮
this.conn = new XHConn(); //AJAX对象
if (!this.conn) alert("XMLHTTP not available. Try a newer/better
browser.");
this.serverUrl = null; //服务端请求路径
this.can = false; //聊天室初始化是否正常
this.nickName = '匿名'; //登陆昵称
this.onlineCount = -1; //在线人数
this.createChatRoom();
VAR = 'act=logout&nick=' + this.nickName;
URL = this.serverUrl;
if ( typeof window.addEventListener != "undefined" )
window.addEventListener( "onbeforeunload", this.logout1,
false );
// IE
else if ( typeof window.attachEvent != "undefined" ) {
window.attachEvent( "onbeforeunload", this.logout1);
}
else {
if ( window.onbeforeunload != null ) {
var oldOnunload = window.onbeforeunload;
window.onbeforeunload = function ( e ) {
oldOnunload( e );
this.logout1;
};
}
else
window.onbeforeunload = this.logout1;
}
return this;
}
//创建聊天相关的DOM对象
ChatRoom.prototype.createChatRoom = function() {
if (!this.parentWin || this.parentWin == null || typeof
(this.parentWin) != 'object') {
alert('无法加载聊天窗口,请查看调用代码是否正确');
return;
}
this.createStyle();
this.parentWin.innerHTML = '请输入你的昵称:<input type="text"
size="10"> <input type="button" onclick="'
+ this.obj + '.loging();" value="登陆"><div class="chatroom"></div><input
type="text" style="width:' + (this.style.width - 40) +
';" onkeypress="if(event.keyCode==13)' + this.obj + '.sendChat();"> <button
onclick="' + this.obj + '.sendChat();">发送</button>';
this.login = this.parentWin.getElementsByTagName('input')[0];
this.loginBtn = this.parentWin.getElementsByTagName('input')[1];
this.input = this.parentWin.getElementsByTagName('input')[2];
this.chatWin = this.parentWin.getElementsByTagName('div')[0];
var o = document.getElementsByTagName("script");
for (var i = 0; i < o.length; i++) {
len = o[i].src.indexOf('chatRoom.asp');
if (len > -1) {
this.serverUrl = o[i].src.substring(0, len + 12);
break;
}
}
if (!this.serverUrl || this.serverUrl.length == 0) {
alert('程序初始化出错');
retur;
}
this.can = true;
this.getChat(true);
}
//创建相关样式表
ChatRoom.prototype.createStyle = function() {
document.write('<style>');
document.write('.chatroom{');
document.write('width:' + this.style.width + 'px;');
document.write('height:' + this.style.height + 'px;');
document.write('overflow-y:scroll;');
document.write('border:1px solid #000');
document.write('margin:10px;');
document.write('padding-bottom:50px;');
document.write('}');
document.write('.chatroom li{');
document.write('list-style-type:none;');
document.write('padding:3px 0 3px 0;');
document.write('}');
document.write('.self{');
document.write('color:#269926;');
document.write('}');
document.write('</style>');
}
//发送消息
ChatRoom.prototype.sendChat = function() {
if (!this.can) return;
if (!this.logined) {
alert('请先登陆!');
this.login.focus();
return;
}
var msg = this.input.value;
if (msg && msg.length > 0) {
msg = 'act=sendChat&msg=' + this.encode(msg) + '&nick='
+ this.nickName;
this.conn.connect(this.serverUrl, 'POST', msg, this.fnResponse,
this);
this.input.value = '';
}
}
//从服务端取得最新的聊天信息
ChatRoom.prototype.getChat = function(first) {
if (!this.can) return;
if (!this.logined && !first) return;
var sVar = "act=getChat";
this.conn.connect(this.serverUrl, 'POST', sVar, this.fnResponse,
this);
var obj = this;
window.setTimeout(function(){obj.getChat();}, '1000');
}
//登陆聊天室
ChatRoom.prototype.loging = function() {
if (this.loginBtn.value == '退出') {
this.logout();
return;
}
if (!this.can) return;
if (this.login.value.length == 0) {
alert('请输入昵称!');
this.login.focus();
return;
}
if (this.login.value.length > 20) {
alert('昵称太长了吧,最多十个汉字!');
this.login.focus();
this.login.select();
return;
}
var sVar = 'act=login&nick=' + this.login.value;
this.nickName = this.login.value;
VAR = 'act=logout&nick=' + this.nickName;
this.conn.connect(this.serverUrl, 'POST', sVar, this.fnResponse,
this);
}
//退出聊天室
ChatRoom.prototype.logout = function() {
if (!this.can) return;
if (!this.logined) return;
var sVar = 'act=logout&nick=' + this.nickName;
this.conn.connect(this.serverUrl, 'POST', sVar, this.fnResponse,
this);
this.logined = false;
this.loginBtn.value = '登陆';
}
//退出聊天室1
ChatRoom.prototype.logout1 = function() {
if (document.getElementsByTagName("INPUT")[1].value ==
'退出') {
var conn = new XHConn();
conn.connect(URL, 'POST', VAR, function(){}, this);
}
}
//编码字符串
ChatRoom.prototype.encode = function(str) {
return encodeURIComponent(str);
}
//处理AJAX服务端返回的代码
ChatRoom.prototype.fnResponse = function(oXml, parObj)
{
//if (oXml.responseText.length > 0) alert(oXml.responseText);
var xmlDoc = oXml.responseXML.documentElement;
if (xmlDoc && typeof xmlDoc == 'object') {
parObj.parseXML(xmlDoc);
}
}
//解析服务端传回的XML代码,并进行相应操作
ChatRoom.prototype.parseXML = function(xmlDoc) {
var attList = xmlDoc.attributes;
if (attList && attList.length == 2 ) {
if (attList[0].name == 'online')
this.onlineCount = attList[0].value;
if (attList[1].name == 'self')
this.self = attList[1].value;
if (this.self.length > 0) this.logined = true;
}
var arr = xmlDoc.childNodes, newChat, str;
for (var i = 0; i < arr.length; i++) {
if (arr[i] && arr[i].nodeName == 'msg' &&
arr[i].childNodes[0].nodeType == 3 &&
arr[i].childNodes[0].nodeValue.length > 0) {
newChat = document.createElement('LI');
this.chatWin.appendChild(newChat);
str = '';
if (arr[i].attributes[0].name == 'nick') {
if (arr[i].attributes[0].value == this.self)
str += '<span class="self">你说:</span>';
else
str += arr[i].attributes[0].value + '说:';
str += arr[i].childNodes[0].nodeValue;
newChat.innerHTML = str;
this.chatWin.scrollTop = this.chatWin.scrollHeight;
}
} else if (arr[i] && arr[i].nodeName == 'system'
&&
arr[i].childNodes[0].nodeType == 3 &&
arr[i].childNodes[0].nodeValue.length > 0) {
newChat = document.createElement('LI');
this.chatWin.appendChild(newChat);
str = '<span style="color:blue">系统:</span>' + arr[i].childNodes[0].nodeValue;
newChat.innerHTML = str;
this.chatWin.scrollTop = this.chatWin.scrollHeight;
} else if (arr[i] && arr[i].nodeName == 'login'
&&
arr[i].childNodes[0].nodeType == 3 &&
arr[i].childNodes[0].nodeValue.length > 0) {
if (arr[i].childNodes[0].nodeValue == 'OK') {
this.logined = true;
this.loginBtn.value = '退出';
this.getChat();
} else {
alert(arr[i].childNodes[0].nodeValue);
}
}
}
}
<%End If%>