ajax中数据传递的另一种模式:xml

XMl
  是现代计算机中无所不在的数据格式,Ajax应用所处的Web浏览器环境,特别是XMLHttpRequest对象,对于处理XML提供了很好的本地支持,如果XZmlHttpRequest接收到了一个XML内容类型,例如application/xml或test/xml,它将会响应表现为一个DOM!
下面看段脚本:

    <script>
    var offset=8;
    function showPopup(name,description)
    {
   
    var win=new DataPopup(name,description,offset,offset,320,320);
    offset+=32;
   
    }
    function DataPopup(name,description,x,y,w,h)
    {
    var bod=document.createElement("div");
    document.body.appendChild(bod);
    this.contentDiv=document.createElement("div");
    this.contentDiv.className="windContents";
    this.contentDiv.innerHTML=description;
    bod.appendChild(this.contentDiv);
    this.win=new windows.Window(bod,name,x,y,w,h);
    }
   
    function showInfo(event)
    {
    var planet=this.id;
    var scriptUrl=planet+".xml";
    new net.ContentLoader(scriptUrl,parseXML);
    }
   
    function parseXML()
    {
    var name="";
    var descrip="";
    var xmlDoc=this.req.responseXML;
    var elDocRoot=xmlDoc.getElementsByTagName("planet")[0];
    if(elDocRoot)
    {
    attrs=elDocRoot.attributes;
    name=attrs.getNamedItem("name").value;
    var ptype=attrs.getNamedItem("type").value;
    if(ptype)
    {
    descrip+="<h2>"+ptype+"</h2>";
    }
    descrip+="<ul>";
    for(var i=0;i<elDocRoot.childNodes.length;i++)
    {
    elChild=elDocRoot.childNodes[i];
    if(elChild.nodeName=="info")
    {
    descrip+="<li>"+elChild.firstChild.data+"</li>\n";
    }
    }
    descrip+="</ul>";
    }
    else{
    alert("no document");
    }
    top.showPopup(name,descrip);
    }
    </script>


showInfo函数简单地打开一个封装在ContentLoader对象中的 XMLHttpRequest对象,提供parseXML()方法作为回调。这个回调函数比evalScript()方法稍微麻烦一些,因为我们需要在响应的DOM中导航,从中抽取出数据,然后再手工调用showPopup()方法,!以xml数据为中心的应用中可以使用这些数据!
xml的一个很大优点是有助于对信息进行结构话!这个脚本中用parseXMl()将函数中将他们转换成一段HTML的无语立标!

原文地址:https://www.cnblogs.com/paper/p/1533252.html