AJAX应用中怎样确保得到XML DOM对象?

使返回的xml数据能够作为XML DOM对象来用,需要这么几件事情:

1、服务器返回的头部信息需要 设置 Content-Type: text/xml

2、返回的xml结构中需要有个documentElmement节点,这样可以保证各浏览器之间的兼容。举例来说:
(建议你客户端和服务器端全部使用UTF-8编码,减少因编码问题引起的莫名奇妙问题)

<?xml version="0.1" encoding="UTF-8"?>
<res>
  <data><![CDATA[abc123]]></data>
</res>

这里 res就是documentElement

3、以上面的xml为例,客户端收到responseXML对象后,首先

var doc = responseXML.documentElement; //得到 res,这步很重要
var d = doc.getElementsByTagName('data')[0];
alert( getNodeValue(d) ); //  show 'abc123'

//----------------------
function getNodeValue(node)
{
  if(node && node.hasChildNodes()){
    //return node.firstChild.nodeValue;
    var s="";
    //Mozilla has many textnodes with a size of 4096 chars
    // each instead of one large one.
    //They all need to be concatenated.
    for(var j=0;j<node.childNodes.length;j++){
      s+=new String(node.childNodes.item(j).nodeValue);
    }
    return s;
  }else
    return "";
}

1 条评论 »

  1. chenmoran said,

    2007/7/6 @ 11:24

    收获很大!多谢!

RSS feed for comments on this post · TrackBack URI

发表看法

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word