问题:希望高手帮忙找一下原因,谢谢
代码问题点:聊天框:响应信息:所有源码文件:
login.php;
LoginController.php;
friendList.php;
chatRoom.php;
MessageService.class.php;
SendMessageController.php;
GetMessageController.php;
SqlHelper.class.php;
my.js;
代码如下:
login.php;<html>
<head >
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<div style="width: 400px; height: 200px; margin: 100px auto; background-color: #ddd;">
    <h1>欢迎登录聊天室</h1>
    <form action="LoginController.php" method="post">
        用户名:<input type="text" name="username" /><br/>
        密  码:<input type="password" name="passwd"/><br/>
        <input type="submit" value="登录聊天室"/><br/>
    </form>
</div>
</html>
LoginController.php;<?php$loginUser=$_POST['username'];
$pwd=$_POST['passwd'];//判断
if($pwd=="123"){
   //用session保存登陆人的名字。
   session_start();
   $_SESSION['loginuser']=$loginUser;
//跳转到好友列表
   header("Location:friendList.php");
}else{
   header("Location:login.php");}
?>
friendList.php;
<html>
<head >
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="my.js"></script>
        <script type="text/javascript">
            function change1(val,obj){
                if(val=="over"){
                    obj.style.color="red";
                    obj.style.cursor="hand";
                }else if(val=="out"){
                    obj.style.color="black";
                }
            }            //响应点击新的窗口
            function openChatRoom(obj){
            //因为window.open是get方式提交,所以到服务器后变成乱码,所以需要编码(我自己用没有遇到这个问题)
            window.open("chatRoom.php?username="+encodeURI(obj.innerText),"_blank")
            }
        </script>
</head>
  <h1>好友列表</h1>
    <ul>
        <li onmouseover="change1('over',this)" onmouseout="change1('out',this)" onclick="openChatRoom(this)">宋江</li>
        <li onmouseover="change1('over',this)" onmouseout="change1('out',this)" onclick="openChatRoom(this)">张飞</li>
        <li onmouseover="change1('over',this)" onmouseout="change1('out',this)" onclick="openChatRoom(this)">小倩</li>
    </ul>
</html>
chatRoom.php;
<html>
<head >
<?php
//接收window,open传递的用户名
$username=$_GET['username'];
//若出现接收信息多出空格,则可以使用trim,去除首尾字符串的空白字符,如下代码。
//$username=trim($username);//取出session中保存登陆人的名字。
session_start();
$loginuser=$_SESSION['loginuser'];?>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="my.js"></script>
    <script type="text/javascript">
        //window.resizeTo(500,500);
window.setInterval("getMessage()",5000); function getMessage(){
var myXMLHttpRequest=getXMLHttpObject();
if(myXMLHttpRequest){
var url="/chatroom/GetMessageController.php";
var data="getter=<?php echo $loginuser ?>&sender=<?php echo $username ?>";
myXMLHttpRequest.open("post",url,true);
myXMLHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
myXMLHttpRequest.onreadystatechange=function(){
                   if(myXMLHttpRequest.readyState==4&&myXMLHttpRequest.status==200){
   //接收
   //window.alert(myXMLHttpRequest.responseText);
   var mesRes=myXMLHttpRequest.responseXML;
   //取出con和sendTime
   var cons=mesRes.getElementsByTagName("con");
   var sendTimes=mesRes.getElementsByTagName("sendTime");
   //window.alert(mesRes);
   if(cons.length!=0){
   //可以处理数据了,有多少条就显示多少条
   for(var i=0;i<cons.length;i++){
   var str="<?php echo $username; ?>对<?php echo $loginuser; ?>说:"+cons[i].childNodes[0].nodeValue+" "+sendTimes[i].childNodes[0].nodeValue;
   $("mycons").value+=str+"\r\n";
   }
   }
                   }
                }
//发送
myXMLHttpRequest.send(data);
}
}        function sendMessage(){            var myXMLHttpRequest=getXMLHttpObject();            if(myXMLHttpRequest){
                var url="/chatroom/SendMessageController.php";
                var data="con="+$("con").value+"&getter=<?php echo $username;  ?>&sender=<?php echo $loginuser; ?>";
                window.alert(data);
                myXMLHttpRequest.open("post",url,true);
                myXMLHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                myXMLHttpRequest.onreadystatechange=function(){
                   if(myXMLHttpRequest.readyState==4&&myXMLHttpRequest.status==200){                   }
                }
//发送
myXMLHttpRequest.send(data);
//把你的画显示到聊天框
$("mycons").value+="你 对 <?php echo $username; ?>说:"+$("con").value+"    "+new Date().toLocaleString()+"\r\n";            }
        }
    </script>
</head><div style="width: 700px; height: 400px; margin: 100px auto; background-color: #ddd;">
    <h1>聊天室(<font color="red"><?php echo $loginuser;   ?></font>正在和<font color="red"><?php echo $username; ?></font>聊天)</h1>
    <textarea cols="60" rows="10" id="mycons"></textarea><br>
    <input type="text" id="con" style="width:300px;"/>
    <input type="button" value="发送信息" onclick="sendMessage()"/>
</div>
</html>
MessageService.class.php;
<?php
    require_once('SqlHelper.class.php');
    class MessageService{
//添加信息到数据库
function addMessage($sender,$getter,$con){

$sql="insert into messages (sender,getter,content,sendTime) values('$sender','$getter','$con',now())";

//file_put_contents("D:/wamp/www/chatroom/mylog.log","sql=".$sql."\r\n",FILE_APPEND); $sqlHelper=new SqlHelper();
return $sqlHelper->execute_dml($sql);
} //获取数据,并把数据组装好,返回给客户端(聊天室)
function getMessage($getter,$sender){
$sql="select * from messages where getter='$getter' and sender='$sender' and isGet=0";
//file_put_contents("D:/wamp/www/chatroom/mylog.log",$sql."\r\n",FILE_APPEND);
$sqlHelper=new SqlHelper();
$array=$sqlHelper->execute_dql2($sql);
//file_put_contents("D:/wamp/www/chatroom/mylog.log",$array."\r\n",FILE_APPEND);
//难点,如何拼接xml格式
$messageInfo="<meses>";
for($i=0;$i<count($array);$i++){
$row=$array[$i];
$messageInfo.="<mesid>{$row['id']}</mesid><sender>{$row['sender']}</sender><getter>{$row['getter']}</getter><con>{$row['content']}</con><sendTime>{$row['sendTime']}</sendTime>"; }
$messageInfo.="</meses>";
$sql="update messages set isGet=1 where getter='$getter' and sender='$sender' ";
$sqlHelper->execute_dml($sql);

//输出日志
//file_put_contents("D:/wamp/www/chatroom/mylog.log",$messageInfo."\r\n",FILE_APPEND);
$sqlHelper->close_connect();
return $messageInfo;
}
}?>
SendMessageController.php;
<?php
    
    require_once 'MessageService.class.php';
//接收信息
$sender=$_POST['sender'];
$getter=$_POST['getter'];
$con=$_POST['con']; //file_put_contents("D:/wamp/www/chatroom/mylog.log",$sender."-".$getter."-".$con."\r\n",FILE_APPEND); //创建对象
$messageService=new MessageService();
$res=$messageService->addMessage($sender,$getter,$con);
if($res==1){
echo "ok";
}else{
echo "err";
}
//file_put_contents("D:/wamp/www/chatroom/mylog.log",$sender."-".$getter."-".$con."-".$res."\r\n",FILE_APPEND);?>
GetMessageController.php;
<?php
//这两句话很重要,第一句告诉浏览器返回的数据是XML格式,第二句告诉浏览器不要缓存数据
header("content-type:text/xml;charset=utf-8");
header("Cache-Control:no-cache");
require_once 'MessageService.class.php';
//这个控制器,专门用于响应用户取数据的请求
$getter=$_POST['getter'];
$sender=$_POST['sender'];
//调用messageServer来获取数据
$messageService=new MessageService();
$mesList=$messageService->getMessage($getter,$sender);
//file_put_contents("D:/wamp/www/chatroom/mylog.log",$mesList."\r\n",FILE_APPEND);
echo $mesList;
?>
SqlHelper.class.php;
<?php
   //这是一个工具类,作用是完成对数据库的操作
   class SqlHelper {
   public $conn;
   public $dbname="chat";
   public $username="root";
   public $password="";
   public $host="localhost";    public function __construct(){
   $this->conn=mysql_connect($this->host,$this->username,$this->password);
   if(!$this->conn){
   die("连接失败".mysql_error());
   }
   mysql_select_db($this->dbname,$this->conn);
   }    //执行dql语句
   public function execute_dql($sql){
   $res=mysql_query($sql,$this->conn) or die($sql);
   return $res;
   }    //执行dql语句,但是返回的是一个数组
   public function execute_dql2($sql){
   $arr=array();
   $res=mysql_query($sql,$this->conn) or die(mysql_error());
   //把$res=>$arr 把结果集内容转移到一个数组中。
   while($row=mysql_fetch_assoc($res)){
   $arr[]=$row;
   }
   //这里就可以把$res关闭
   mysql_free_result($res);
   return $arr;
   }    //执行dml语句 更新 插入 删除语句
   public function execute_dml($sql){
   $b=mysql_query($sql,$this->conn) or die(mysql_error());
   if(!$b){
   return 0; //失败
   }else{
   if(mysql_affected_rows($this->conn)>0){
   return 1; //表示执行OK
   }else{
   return 2;//表示没有行受到影响
   }
   }
   }
   //关闭连接的方法
   public function close_connect(){
   if(!empty($this->conn)){
   mysql_close($this->conn);
   }
   }
   }?>
my.js;
//创建ajax引擎
function getXMLHttpObject(){
    var xmlHttpRequest;
    //不同浏览器获取对象XMLHttpRequest方法不一样
    if(window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlHttpRequest=new XMLHttpRequest();
    }else{
        // code for IE6, IE5
        xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlHttpRequest;
}
function $(id){
    return document.getElementById(id);
}

解决方案 »

  1.   

     问题太长了,建议浓缩出关键部分再提问,另外建议用前端框架如jquery解决,不要浪费这些没必要的工作量
      

  2.   

    问题就是:myXMLHttpRequest.responseXML为什么返回null?后面我只是把代码都贴了出来,方便你们问题查找,量是有点大不看也可以,图片里标有代码逻辑和出错的地方
      

  3.   

    吧  responseXML换成responseText;