用Ajax编写的聊天室

一、服务器端处理:

服务器端主要用来处理用户提交的信息以及输出返回:

①首先需要在服务器端链接数据库。

②如果有用户提交新信息,则把信息插入数据库,同时删除旧数据的数据信息(保持数据库中只有10信息)。

③最后从中获取新的信息并以XML格式输出。

服务器端代码:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <status>1</status>
    <time>1170323512</time>
    <message>
        <author>张三</author>
        <text>沙发!</text>
    </message>
    <message>
        <author>李四</author>
        <text>板凳!</text>
    </message>
</response>

 

二、客户端处理:

主要做两项工作:

①提交用户聊天信息,然后处理服务器端返回的聊天信息,将信息实时呈现出来。

②每隔一定时间发起查询数据库的请求,然后处理服务器端返回的聊天信息,将信息实时呈现出来。

客户端代码:

<?xml version="1.0" encoding="UTF-8"?>
<!--引入jQuery-->
<!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" xml:lang="en" lang="en">
<head>
    <script type="text/javascript">
        timestamp=0;
        updateMsg();
        $("#chatform").submit(function(){
            $.post("backend.php",{//"backend.php"是指服务器端文件,{……}中是从页面发送过来的信息,function是要返回到页面的信息
                message:$("#msg").val(),
                name:$("#author").val(),
                action:"postmsg",
                time:"timestamp"
            },function(xml){
                $("#msg").val("");//清空信息文本框内容
                addMessages(xml)//调用解析xml的文件(响应返回的XML,且能重复使用)
            });
            return false;//阻止表单提交
        });
        function addMessage(xml){
            if($("status",xml).text==2)
            return true;
            timestamp = $("time",xml).val();//更新时间戳
            $("message",xml).each(function(){
                var author = $("author",xml).text();
                var content = $("content",xml).text();
                var htmlcode = "<strong>"+author+"</strong>:"+content+"<br/>";
                $("#messagewindow").prepend(htmlcode);//添加到文档中
            });
        }
        function updateMsg(){
            $.post("backend.php",{time:timestamp},function(xml){
                $("#loading").remove();
                addMessage(xml);
            });
            setTimeout('updateMsg()',4000);//每隔4秒读取一次
        }
    </script>
    <title>聊天室</title>
</head>
<body>
    <div id="wrapper">
        <p id="messagewindow"><span id="loading">加载中……</span></p>
        <form id="chatform" action="">
            姓名:<input type="text" id="author" size="50"/><br/>
            内容:<input type="text" id="msg" size="50"/><br/>
            <input type="submit" value="发送"/><br/>
        </form>
    </div>
</body>
</html>

 

posted @ 2016-11-04 10:39  liq123  阅读(133)  评论(0)    收藏  举报