如何处理对方法getElementsByTagname的调用为null

时间:2011-08-10 13:46:30

标签: html xml ajax

我有这段代码:

<script language="JavaScript" type="text/javascript">
    var sendReq = getXmlHttpRequestObject();
    var receiveReq = getXmlHttpRequestObject();
    var lastMessage = 0;
    var mTimer;
    function handleReceiveChat() 
    {
       if (receiveReq.readyState == 4)
       {
          var chat_div = document.getElementById('div_chat');    
          var xmldoc = receiveReq.responseXML;     
          var message_nodes = xmldoc.getElementsByTagName("message");
          //more code
       }
    }


    function getChatText()
    {
        if (receiveReq.readyState == 4 || receiveReq.readyState == 0) 
        {
           receiveReq.open("GET", 'getChat_xml.php?chat=1&last=' + lastMessage, true);
           receiveReq.onreadystatechange = handleReceiveChat; 
           receiveReq.send(null);
        }
    }
</script>

在getChat_xml中我有这个:

$xml = '<?xml version="1.0" ?><root>';
if(!isset($_GET['chat'])) 
{
$xml .='Your are not currently in a chat session.  <a href="">Enter a chat session here</a>';
$xml .= '<message id="0">';
$xml .= '<user>Admin</user>';
$xml .= '<text>Your are not currently in a chat session.  &lt;a href=""&gt;Enter a chat session here&lt;/a&gt;</text>';
$xml .= '<time>' . date('h:i') . '</time>';
$xml .= '</message>';
}
else
{
$last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
$sql = "SELECT message_id, user_name, message, date_format(post_time, '%h:%i') as post_time" . 
    " FROM message WHERE chat_id = " . db_input($_GET['chat']) . " AND message_id > " . $last;
$message_query = db_query($sql);
//Loop through each message and create an XML message node for each.
while($message_array = db_fetch_array($message_query))
    {
    $xml .= '<message id="' . $message_array['message_id'] . '">';
    $xml .= '<user>' . htmlspecialchars($message_array['user_name']) . '</user>';
    $xml .= '<text>' . htmlspecialchars($message_array['message']) . '</text>';
    $xml .= '<time>' . $message_array['post_time'] . '</time>';
    $xml .= '</message>';
}
}
$xml .= '</root>';

有人可以帮忙吗?不明白这是如何工作的 感谢

3 个答案:

答案 0 :(得分:0)

也许是一个愚蠢的问题,但你实际上是echo $xml getChat_xml.php档案中的xmldoc.getElementsByTagName("message")吗?我可以看到null返回<message>,因为它找不到任何{{1}}元素,因为PHP从未输出过DOM。直接查看文件会发生什么? :http://www.yoursite.com/getChat_xml.php?chat=1&last=xxx

答案 1 :(得分:0)

在黑暗中只是一枪,但试试这个:

function handleReceiveChat() 
{
   if (receiveReq.readyState == 4)
   {
      var chat_div = document.getElementById('div_chat');    
      var xmldoc = receiveReq.responseXML;     
      var message_nodes = xmldoc.getElementsByTagName("message");

      if (message_nodes)
      {
          //more code
      } 
   }
}

答案 2 :(得分:0)

看到你发布的代码后,会想到这些问题......

  1. 您实际上没有添加echo $xml;来输出生成的XML。
  2. 即使在添加'echo'语句后,由于PHP代码中的某些错误(可能是SQL查询),您可能会得到null responseXML(因此未定义getElementsByTagName
  3. 即使你的PHP代码是正确的,你也会得到null responseXML,因为你没有发送适当的内容标题(header('Content-Type: text/xml');)。