AJAX聊天室小DEMO(讨厌JS,IE下有问题已解决)

太闲啦,太闲啦,连续一月没上课了.不知他们想我没.昨QQ上一JJ给我看她写的聊天室,刷的眼难受,让我帮她写个不刷新的给她看.就是闲嘛,一切都是Teach Myself,从来没人指导过我.想帮帮她.偶尔有个人帮我我也很感动.顺便自个学点东西吧.一直没用在CNBLOGS上东西,上次发错了,发到首页上去了,写的一个数据结构的代码片断,一大哥骂我不写注释,原来首页就是那个意思,现在我没事就往首页上发,旨在寻人骂我.我是菜鸟我怕谁,PS:在此之前我只懂点AJAX原理,对框架一无所知.以下是DEMO.发上来主要是给大家批评的还有点问题想请教.
我用XML做一个队列类似的东西存储10条信息.先入先出.再用ajax取出信息反应到聊天窗口,聊天窗口1秒刷一次
default.aspx页 表单部分
下面是ajax_chat.js代码
            var sendReq = createAjaxObj();
            
var receiveReq = createAjaxObj();
            
var mTimer;
            
var lastMessage = 0;  //最后一条Message ID值
            var n_messages=0;  //XML中的MESSAGE节点数,我设的是10条
            var diff=0;
            
var chat_div = document.getElementById('div_chat');
            
function startChat()
             
{
             
var content=document.getElementById('div_chat');  
                document.getElementById('txt_message').focus();
                 
//为什么我直接用chat_div不行,非要重定义一个content变量才行?晕哦.
                  content.innerHTML="<font color=red>Solo's chatroom demo,chang u name first!</font><br/>";
                
//每隔2秒执行一次取文本的命令
                setInterval("getChatText()",1000);
                
            }
        
function createAjaxObj()
{
//创建兼容的的xmlhttp对象
    var xmlhttp;
     
try
        
{
        xmlhttp
=new ActiveObject('Msxml2.XMLHTTP');
        }

        
catch(e)
        
{
            
try
            
{
            xmlhttp
=new ActiveObject('Microsoft.XMLHTTP');
            }

            
catch(e)
            
{
                
try
                
{
                xmlhttp
=new XMLHttpRequest();
                }

                
catch(e){}
            }

        }

       
return xmlhttp;
}

//获取XML文本
function getChatText() 
{

//判断上次请求的状态是否完成或是还未发送请求
    if (receiveReq.readyState == 4 || receiveReq.readyState == 0{
        
//从content.xml获取聊天内容
    receiveReq.open("get","content.xml");
    
//当请求状态改变时调用handleReceiveChat方法
        receiveReq.onreadystatechange = handleReceiveChat; 
        receiveReq.send(
null);//因为是get方法所以发送请求null
    }
            
}

function handleReceiveChat() 
{

    
if (receiveReq.readyState == 4)
     
{//此时请求已经完成
       //获得显示消息的图曾层元素
        var chat_div = document.getElementById('div_chat');
        
//获得返回后的XML文件
        var xmldoc = receiveReq.responseXML;
        
//得到所有的新的消息记录
        var message_nodes = xmldoc.getElementsByTagName("message"); 
        n_messages 
= message_nodes.length;
        

        
var id=message_nodes[n_messages-1].getAttribute("id");
        lastMessage
=getCookie("lastMessage");
        
if(lastMessage==null)
        
{
            addCookie(
"lastMessage","0",10);
            lastMessage
=getCookie("lastMessage");
         }

         
         
if(id-lastMessage>=n_messages)
         
{
          
var i=0;
            diff
=n_messages;
            
while((message_nodes[n_messages-1].getAttribute("id")>=lastMessage)&&i<=diff-1)
            
{
                
var user_node = message_nodes[i].getElementsByTagName("user");
                
var text_node = message_nodes[i].getElementsByTagName("text");
                
var time_node = message_nodes[i].getElementsByTagName("time");
                chat_div.innerHTML 
+= '(<font class="chatUser">'+user_node[0].firstChild.nodeValue + '</font>)&nbsp;said at &nbsp;';
                chat_div.innerHTML 
+= '<font class="chatTime">+ time_node[0].firstChild.nodeValue + '</font><br />';
                chat_div.innerHTML 
+= '<span class="title">'+text_node[0].firstChild.nodeValue + '</span><br />';
                chat_div.scrollTop 
= chat_div.scrollHeight;
                
//每循环一条消息,记录到id到,lastMessage的cookie中        
                lastMessage = (message_nodes[i].getAttribute("id"));
                deleteCookie(
"lastMessage");
                addCookie(
"lastMessage",lastMessage,5);
                
                 i
++;
              
// alert("this lastMessage:"+lastMessage);    
                 
            }

         }

         
else
         
{
            
while(message_nodes[n_messages-1].getAttribute("id")>lastMessage)
            
{
                
var dif=message_nodes[n_messages-1].getAttribute("id")-lastMessage;
                
var temp=n_messages-dif;
                
if(dif!=0)
                
{
                
var user_node = message_nodes[temp].getElementsByTagName("user");
                
var text_node = message_nodes[temp].getElementsByTagName("text");
                
var time_node = message_nodes[temp].getElementsByTagName("time");
                chat_div.innerHTML 
+= '(<font class="chatUser">'+user_node[0].firstChild.nodeValue + '</font>)&nbsp;said at &nbsp;';
                chat_div.innerHTML 
+= '<font class="chatTime">+ time_node[0].firstChild.nodeValue + '</font><br />';
                chat_div.innerHTML 
+= '<span class="title">'+text_node[0].firstChild.nodeValue + '</span><br />';
                chat_div.scrollTop 
= chat_div.scrollHeight;
                
//每循环一条消息,记录到全局变量lastMessage的Cookie中        
          
                deleteCookie(
"lastMessage");
                 lastMessage
++;
                addCookie(
"lastMessage",lastMessage,1);
               
                temp
++;
                }

              
               
//alert("this lastMessage:"+lastMessage+"getAttribute:"+message_nodes[n_messages-1].getAttribute("id"));    
                 
            }

         }

         
       
    }

}

//发送聊天内容
function sendChatText()
 
{
       
if(document.getElementById('userName').value=='annoymous')
       
{
            alert(
"Input your name!");
            
return;
       }

//如果输入的消息为空,提示用户输入
    if(document.getElementById('txt_message').value == '')
     
{
        alert(
"You have not entered a message");
        
return;
    }

    
//判断上次发送消息请求的状态是否完成或是还未发送请求
    if (sendReq.readyState == 4 || sendReq.readyState == 0
    
{
       
//保存消息的服务器地址
        var submitURL = "sendMessage.aspx?userName="+document.getElementById('userName').value+"&msg="+document.getElementById('txt_message').value;
        sendReq.open(
"POST",  submitURL , true);//建立请求连接
        sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        sendReq.onreadystatechange 
= handleSendChat; //当请求状态改变时调用handleSendChat方法
        sendReq.send(null);//发送请求
       
        document.getElementById('txt_message').value 
= '';//设置提交消息文本框为空
      
    }
                            
}

function handleSendChat()
 
{
 
//发送后强制执行一次获取聊天内容一次

    
//lastMessage =getCookie("lastMessage");
    getChatText();
}


//三个JS常用的函数网上抄的
function addCookie(name,value,expireMin)
{
    
var cookieString=name+"="+escape(value);
    
//判断是否设置过期时间
    if(expireMin>0){
        
var date=new Date();
        date.setTime(date.getTime
+expireMin*60*1000);
        cookieString
=cookieString+"; expire="+date.toGMTString();
    }

    document.cookie
=cookieString;
}

function getCookie(name)
{
//获取指定名称的Cookie值
    var strCookie=document.cookie;
    
var arrCookie=strCookie.split(";");
    
for(var i=0;i<arrCookie.length;i++)
    
{
        
var arr=arrCookie[i].split("=");
        
if(arr[0]==name)
        
return arr[1];
    }

    
return null;
}

  
function deleteCookie(name)
  
{
     
var expires=new Date();
     expires.setTime(expires.getTime()
-1);
     addCookie(name,
"Delete Cookie",expires);
   }



点击发送 sendMessage.aspx
public partial class sendMessage : System.Web.UI.Page
{
    XmlDocument doc;
    
string filePath; //聊天内容存储的XML文件
    protected void Page_Load(object sender, EventArgs e)
    
{
        filePath 
= Server.MapPath("content.xml");
        doc 
= new XmlDocument();
        doc.Load(filePath);
        
if (!IsPostBack)
        
{
            
if (Application["lock"].ToString() == "unlock")
             
{
                Application[
"lock"= "lock"//锁定防止多用户操作
                int num = GetLastMsgId();
                num
++;
                
string msgid = num.ToString();

                
if (Request.QueryString["userName"!= string.Empty && Request.QueryString["msg"!= string.Empty)
                
{
                    
if (GetMsgNum() < 10)
                    
{
                        
//如果消息少于10条,添加结点
                        AddInLast(msgid, Request.QueryString["userName"].Trim(), Request.QueryString["msg"].Trim());
                    }

                    
else
                    
{
                        
//如果消息少于10条,弹出第一条,再向末结点后添加结点
                        DelFirst();
                        AddInLast(msgid, Request.QueryString[
"userName"].Trim(), Request.QueryString["msg"].Trim());
                    }

                    
                }

                Application[
"lock"= "unlock"//解锁
            }

        }

        doc 
= null;
    }

    
public void DelFirst()
    
{
        
//如果超过10条弹出第一条
        XmlNode node = doc.DocumentElement;
       
        node.RemoveChild(node.FirstChild);
    }

    
public int GetMsgNum()
    
{
        
//Message数目
        XmlNode node = doc.DocumentElement;
        
return node.ChildNodes.Count;
    }

    
public int GetLastMsgId()
    
{
        
//最后一条ID
        XmlNode node = doc.DocumentElement;
        XmlElement last 
= (XmlElement)node.LastChild;
        
return Convert.ToInt32(last.GetAttribute("id"));
    }

    
public void AddInLast(string id,string strUser,string strContent)
    
{
        
//加入新建Messag结点
        XmlNode node = doc.DocumentElement;
        XmlElement msgNode 
= doc.CreateElement("message");
        msgNode.SetAttribute(
"id",id);
        node.AppendChild(msgNode);


        XmlElement eleUser 
= doc.CreateElement("user");
        XmlText textUser 
= doc.CreateTextNode(strUser);
        eleUser.AppendChild(textUser);
        msgNode.AppendChild(eleUser);

        XmlElement eleContent 
= doc.CreateElement("text");
        XmlText textText 
= doc.CreateTextNode(strContent);
        eleContent.AppendChild(textText);
        msgNode.AppendChild(eleContent);

        XmlElement eleTime 
= doc.CreateElement("time");
        XmlText textTime 
= doc.CreateTextNode(DateTime.Now.ToString());
        eleTime.AppendChild(textTime);
        msgNode.AppendChild(eleTime);

        doc.Save(filePath);

    }

}


content.xml结构:
<?xml version="1.0" encoding="utf-8"?>
<root>

  
<message id="125">
    
<user>test</user>
    
<text>test</text>
    
<time>2006-12-23 16:06:07</time>
  
</message>
</root>
解决方案:/Files/fancystyle/chat.rar

posted on 2006-12-23 19:48  Haozes  阅读(1756)  评论(2编辑  收藏  举报