AJAX初级聊天室代码

很早就想发出来了,一直以来都没什么时间,今天偷个空先把代码发上面,明天来写注释.

还是那句话,AJAX是一种应用,而不是一个专门的技术,我认为做做DEMO要的是速度,要让看的人好理解,而JS是最基本的WEB语言,相信比起其他的语言来说,要明了很多,所以我还是选择用JS写前后台代码.但并不代表我不会其他的语言,程序关键还是在于自我对实现的想法,而用什么语言,好比选择工具一样,我用菜刀可以做,用瑞士军刀也可以做,关键是要看在什么场合.

再就AJAX实际上首要考虑的是人性化,人机交互的便利才是他的优势,否则我还是劝你使用FLASH的AS来的更快.

记住这个词--认知潜意识.千万不要让用户感觉到操作的不适应,你也一定要想在用户的前面,也许这就是程序不智能的位置.
如果你喜欢的话可以继续开发这个东西,更希望你能够注明一下转载出处,我会觉得非常地高兴,并写出更多更好的东西.

首页HTML代码:请保存为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>Chating Beta_0.3.23</title>
<link href="images/chatstyle.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="images/chat.js"></script>
<script type="text/javascript" src="images/display.js"></script>
</head>
<body>
<div id="loadifo"></div>
<div class="header">Chating Beta_0.3.23</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="inputs" 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>

CSS文件:请保存为 images/chatstyle.css

程序代码

body{
    margin: 0px;
    padding: 0px;
    font-size: 9pt;
    background-image: url(JD112.jpg);
    background-position: center center;
}
#outmain{
    height: 400px;
    font-size: 9pt;
    overflow-y: scroll;
    overflow-x: hidden;
    SCROLLBAR-ARROW-COLOR:#FF9900;
    SCROLLBAR-FACE-COLOR:#FFF9E1;
    SCROLLBAR-DARKSHADOW-COLOR:#FF9900;
    SCROLLBAR-HIGHLIGHT-COLOR:#FFFFFF;
    SCROLLBAR-3DLIGHT-COLOR:#FF9900;
    SCROLLBAR-SHADOW-COLOR:#FFFFFF;
    SCROLLBAR-TRACK-COLOR:#FFF9E1;
}
#chatmain{}
#outs{
    width: 540px;
    margin-right: auto;
    margin-left: auto;
    padding: 10px;
    margin-top: 10px;
    margin-bottom: 10px;
    background-color: #FFF9E1;
    border: 1px solid #AAA;
    clear: both;
}
.in{
    text-align: center;
}

.names{
    border: 1px solid #AAA;
    background-color: #FFF9E1;
    width: 80px;
    height: 19px;
    line-height: 19px;
}
#loadifo {
    position:absolute;
    top:100px;
    z-index:1;
    right: 10px;
    line-height: 21px;
}
.header{
    height: 60px;
    background-color: #000;
    text-align: center;
    color: #FFF;
    font-weight: bold;
    line-height: 60px;
    font-family: Tahoma;
    font-size: 12pt;
    float: left;
    width: 100%;
    margin-bottom: 20px;
    filter: Alpha(Opacity=50);
    opacity: 0.5;
}
/*效果*/
.btn{
    border: 1px solid #AAA;
    position: absolute;
    margin-top: 2px;
}
.inputs{
    font-size: 9pt;
    background-image: url(input.png);
    background-repeat: no-repeat;
    width: 295px;
    line-height: 21px;
    height: 21px;
    margin: 0px;
    padding: 0px;
    border: 1px solid #AAA;
}
.left,.right{
    background-repeat: no-repeat;
    background-position: center center;
    cursor:pointer;
    border-top-style: none;
    border-right-style: none;
    border-bottom-style: none;
    border-left-style: none;
    background-color: #FFF;
    height: 23px;
    width: 23px;
}
.left{
    background-image: url(l1.gif);
}
.right{
    background-image: url(r1.gif);
}

JS主文件: 请保存为 images/chat.js

程序代码

var nowNum = "m"
function getId(objId){
    return document.getElementById(objId)
}
function getName(objName){
    return document.getElementsByName(objName)[0]
}
var xmldoc
function createxmldoc(){
    if(window.XMLHttpRequest){
        xmldoc = new XMLHttpRequest();
        if(xmldoc.overrideMimeType){
                xmldoc.overrideMimeType("text/xml");
        }
    }else if(window.ActiveXObject){
        try{
            xmldoc = new ActiveXObject("Msxml4.XMLHTTP");
        }catch(e){
            try{
                xmldoc = new ActiveXObject("Msxml3.XMLHTTP");
            }catch(e){
                try{
                    xmldoc = new ActiveXObject("Msxml2.XMLHTTP");
                }catch(e){
                    try{
                        xmldoc = new ActiveXObject("Microsoft.XMLHTTP");
                    }catch(e){}
                }
            }
        }
    }
    if(!xmldoc){
        return false;
    }
}
function createQueryString(names){
    var conts = getName(names).value
    if(conts != ""){
        if(conts == "clear"){
            getId("chatmain").innerHTML = ""
            clean()
            focs()
            return false
        }else{
            return conts
        }
    }else{
        return false
    }
}
function doUsingGet(){
    xmldoc = false
    createxmldoc()
    var url = "chat.asp?clien="+nowNum+"&timeStamp="+new Date().getTime();
    xmldoc.open("GET",url,true);
    xmldoc.onreadystatechange = CheckState;
    xmldoc.setRequestHeader("Content-Type","text/xml;charset=GB2312;");
    xmldoc.send(null);
}
function doUsingPost(){
    createxmldoc()
    if(createQueryString("inputs")){
        if(createQueryString("named")){
            var named = "&named="+createQueryString("named")
        }else{
            var named = ""    
        }
        if(createQueryString("inputs") == "cls"){
            nowNum = "m"
        }
        var url = "chat.asp?clien="+nowNum+"&cont="+createQueryString("inputs")+named+"&timeStamp="+new Date().getTime();
        xmldoc.open("GET",url,true);
        xmldoc.onreadystatechange = CheckState;
        xmldoc.setRequestHeader("Content-Type","text/xml;charset=GB2312;");
        xmldoc.send(null);
        getId("errors").innerHTML = ""
        addChat(createQueryString("inputs"));
        clean()
        focs()
    }else{
        getId("loadifo").innerHTML = "请输入对话内容!"    
        focs()
    }
}
function CheckState(){
    if(xmldoc.readyState == 1){
        //getId("loadifo").innerHTML = "连接服务器"
        }
    else if(xmldoc.readyState == 2){
        //getId("loadifo").innerHTML = "开始加载数据"
        }
    else if(xmldoc.readyState == 3){
        //getId("loadifo").innerHTML = "正在加载数据"
        }
    else if(xmldoc.readyState == 4){
        if(xmldoc.status == 200){
            results()
        }
        else{
            getId("loadifo").innerHTML = "错误"+xmldoc.status;
            focs()
        }
    }
}
function results(){
    resXml()
}
function resXml(){
    var res = xmldoc.responseXML.documentElement;
    var resLen = res.getElementsByTagName("items").length
    if(getTag(res,0,"num") != nowNum){
        //alert(xmldoc.responseXML.xml)
        nowNum = 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(nowNum != "0" && useMag != ""){
                if(useName != ""){
                    var lis = "用户"+ useName + "说:" + useMag + " ["+ useIp + "]"
                }else{
                    var lis = "用户 ["+ useIp + "] 说:" + useMag
                }
            }else{
                var lis = "用户 ["+ useIp + "] 进入聊天室!"
            }
            //var newp = document.createElement("p")
            //newp.innerHTML = lis
            //getId("chatmain").appendChild(newp)
            getId("chatmain").innerHTML += lis + "<br />"
        }
        innerSize()
    }
}
function getTag(response,i,objTagName){
    try{
        var nodeV = response.getElementsByTagName(objTagName)[i].firstChild.nodeValue;
    }catch(e){
        var nodeV = ""
    }
    return nodeV;
}
var overs
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)    
        }
    }
}
window.onload = function(){
    getId("outs").onmousedown = function(){
        overs = 1
    }
    getId("outs").onmouseout = function(){
        overs = 0
        focs()
    }
    getName("inputs").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()
        }
    }

}
setInterval("doUsingGet()",1000)

JS辅助文件:请保存为 images/display.js

程序代码

function overInput(a){
    getId("btn").style.border = "1px solid #54ce43"
    getId("inputs").style.border = "1px solid #54ce43"
    focs()
}
function outInput(a){
    getId("btn").style.border = "1px solid #AAA"
    getId("inputs").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("inputs").focus();
}
function clean(){
    getName("inputs").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("inputs").value = chats[0]
            chatStart = 0.5
        }else{
            chatStart -= 1
            getName("inputs").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("inputs").value = chats[chatStart]
    }
    getId("loadifo").innerHTML = chatStart+","+chats.length
}

主ASP程序文件:请保存为chat.asp

程序代码

<%@LANGUAGE="JAVASCRIPT" CODEPAGE="936"%><%
    Session.CodePage = 936
    Response.ContentType = "application/xml"
    Response.Expires = 0
%><%
function repla(str){
    str = str.replace(/\&/g, "&");
    str = str.replace(/\>/g, ">");
    str = str.replace(/\</g, "<");
    str = str.replace(/\"/g, """);
    str = str.replace(/\'/g, "'");
    return str;
}

var useIp = Request.ServerVariables("REMOTE_ADDR")
if(!Application("counts")){
    Application("counts") = 0
}
if(Request("cont").Count != 0){
    Application.Lock()
        if(Application("counts") < 21){        
            Application("counts") += 1
        }else if(Application("counts") >= 21){
            Application("counts") = 1
        }
        var Cnum = Application("counts")
        var Msgs = repla(Server.HTMLEncode(Request("cont")))
        Application("ips" + Cnum) = useIp +""
        Application("msgs" + Cnum) = Msgs +""
        if(Request("named").Count != 0){
            var names = Request("named")
        }else{
            var names = ""
        }
        Application("names" + Cnum) = names +""
    Application.UnLock()
}
if(Request("cont") == "cls"){
    Application.Contents.RemoveAll()
}
%><?xml version="1.0" encoding="gb2312" ?>
<ppl>
    <num><%=Application("counts")%></num>
    <%
    if(Request("clien") == "m"){
    %>
    <items>
        <ip><%=useIp%></ip>
    </items>
    <%
    }else if(Request("clien") < Application("counts")){
        for(var i=Request("clien"); i<Application("counts"); i++){
            s = Number(i)+1
            var useName = Application("names" + s)
            var useMsg = Application("msgs" + s)
            var useIp = Application("ips" + s)
    %>
    <items>
        <aaa><%=Request("clien")%> <%=s%></aaa>
        <bbb><%=Application("counts")%></bbb>
        <name><%=useName%></name>
        <conts><%=useMsg%></conts>
        <ip><%=useIp%></ip>
    </items>
    <%
        }
    }else if(Request("clien") > Application("counts")){
        for(var i=Request("clien"); i<21; i++){
            var useName = Application("names" + i)
            var useMsg = Application("msgs" + i)
            var useIp = Application("ips" + i)
    %>
    <items>
        <name><%=useName%></name>
        <conts><%=useMsg%></conts>
        <ip><%=useIp%></ip>
    </items>
    <%
        }
        for(var m=1; m<=Application("counts"); m++){
            var useNameM = Application("names" + m)
            var useMsgM = Application("msgs" + m)
            var useIpM = Application("ips" + m)
    %>
    <items>
        <name><%=useNameM%></name>
        <conts><%=useMsgM%></conts>
        <ip><%=useIpM%></ip>
    </items>
    <%
        }
    }else if(Request("clien") == Application("counts")){

}
    %>
</ppl>

全部程序打包下载: 点击下载

(0)

相关推荐

  • php写的简易聊天室代码

    index.php 复制代码 代码如下: <html> <head><Title> 在线聊天 </title></head> <!-- frames --> <frameset rows="70%,*" BORDER="0"> <frame name="top" src="_b.php" marginwidth="0"

  • php socket实现的聊天室代码分享

    /** * patServer * PHP socket server base class * Events that can be handled: * * onStart * * onConnect * * onConnectionRefused * * onClose * * onShutdown * * onReceiveData * * @version 1.1 * @author Stephan Schmidt <schst@php-tools.de> * @package pa

  • Ajax PHP JavaScript MySQL实现简易无刷新在线聊天室

    为更好的运用这两天学到的Ajax的相关的知识,就做了个简单的在线网络聊天室. 思路 实现聊天室,基本上就是通过Ajax来传递数据,让PHP来实现对数据的差入和查找,再交给前端JavaScript实现页面的更新,达到即时聊天的功能. 消息显示区 消息显示区就是一个DIV块,我们会借助Ajax获取到服务器端信息之后,使用JavaScript来更新页面. <h3>消息显示区</h3> <div id="up"> </div> <hr /&

  • PHP实现简单聊天室(附源码)第1/2页

    一,聊天室模块实现1,聊天室主页面窗口设置 复制代码 代码如下: <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><!--载入配置文件--><?php include_once 'config.php';?><!--页面标题--><title><?php echo CHAT_NAME; ?></ti

  • 发布一个迷你php+AJAX聊天程序[聊天室]提供下载

    Mini AJAX Chatroom By Longbill  http://www.longbill.cn  Longbill all rights reserved  2006-08-16 演示地址: http://longbill.cn/down/sample/chat.php 打开文件进行具体设置 使用方法,将这个程序传到服务器上,运行就可以了.  默认的数据保存路径为 rooms/ 目录  调用时后加参数 room=房间名 , 比如 chat.php?room=php,此时就程序就会自

  • 基于HTTP长连接的"服务器推"技术的php 简易聊天室

    首先是首页,包含一个文本输入和一个显示聊天内容的iframe,还有一个隐藏iframe用来提交form表单: 复制代码 代码如下: <?php //chat.php header('cache-control: private'); header('Content-Type: text/html; charset=utf-8'); ?> <html> <script type="text/javascript"> function submitCha

  • PHP聊天室技术

    PHP聊天室技术 黄国辉 1.前言 上网聊天是时下最流行的交友方式.各大网站推出的聊天室都各具特色. 聊天室主要分为WebChat.BBSChat两种.BBSChat是基于Telnet的Tcp协议,是BBS的附设功能,需要客户端Telnet程序.WebChat则采用浏览器方式,实际上是一个多人共同使用的CGI程序.其基本原理是把每个用户的发言通过浏览器传给系统,再由系统收集处理后分发给特定用户. WebChat一般采用Server Push或Client Pull技术.两种技术的区别在于使用不同

  • 使用Angular和Nodejs、socket.io搭建聊天室及多人聊天室

    一,利用Node搭建静态服务器 这个是这个项目的底层支撑部分.用来支持静态资源文件像html, css, gif, jpg, png, javascript, json, plain text等等静态资源的访问.这里面是有一个mime类型的文件映射. mime.js /** * mime类型的 map * @ author Cheng Liufeng * @ date 2014/8/30 * 当请求静态服务器文件的类型 html, css, gif, jpg, png, javascript,

  • 用PHP+MySQL搭建聊天室功能实例代码

    下面,以一个简单的聊天室设计为例,介绍PHP+MySQL在网页开发中的应用 1.总体设计 1.1 构思与规划: 聊天室的基本原理,就是把每个连上同一网页的用户传送的发言数据储存起来,然后将所有的发言数据传给每一用户.也就是说,用数据库汇集每个人的发言,并将数据库中的数据传给每一个人就实现了聊天室的功能. 1.2 表设计 首先使用MySQL建立表chat用来储存用户的发言: 复制代码 代码如下: mysql> CREATE TABLE chat -> (chtime DATATIME, ->

  • nodejs实现的一个简单聊天室功能分享

    今天我来实现一个简单的聊天室,后台用nodejs, 客户端与服务端通信用socket.io,这是一个比较成熟的websocket框架. 初始工作 1.安装express, 用这个来托管socket.io,以及静态页面,命令npm install express --save,--save可以使包添加到package.json文件里. 2.安装socket.io,命令npm install socket.io --save. 编写服务端代码 首先我们通过express来托管网站,并附加到socke

随机推荐