零基础学习AJAX之AJAX的简介和基础(7)


    function getXML(addressXML) {
                var sUrl = addressXML + "?timestamp=" + new Date();
                createXMLHttpRequest();
                xmlHttp.onRecorderStateChange = handleStateChange;
                xmlHttp.open("GET", url);
                xml.send(null);
            }

function handleStateChange() {
                if (xmHttp, readyState == 4 && xmlHttp.status == 200)
                DrawTable(xmlHttp.responseXML); //responseXML获取到xml文档
            }

其中DrawTable()为后勤处理XML的函数,将服务器返回的XML对象responseXML直接作为参数传递,HTML部分如下:

复制代码 代码如下:


    <input type="button" value="获取XML"><br><br>
<table summary="list of members in EE Studay">
    <tr>
        <th scope="col">Name</th>
        <th scope="col">Class</th>
        <th scope="col">Birthday</th>
        <th scope="col">Constellation</th>
        <th scope="col">Mobile</th>
    </tr>
</table>

当用户单击按钮时出发getXML(),并将xml地址1-4.xml作为参数传入

而函数DrawTable()的任务就是把XML中的数据拆分,并重新组装到表格"member"中,代码如下:可以看到处理XML的方法与DOM处理HTML完全相同

复制代码 代码如下:


    function DrawTable(myXML) {
                //用DOM方法操作XML文档
                var oMembers = myXML.getElementsByTagName("member");
                var oMember = "",
                    sName = "",
                    sClass = "",
                    sBirth = "",
                    sConstell = "",
                    sMobile = "";
                for (var i = 0; i < oMembers.length; i++) {
                    oMember = oMembers[i];
                    sName = oMember.getElementsByTagName("name")[0].firstChild.nodeValue;
                    sClass = oMember.getElementsByTagName("class")[0].firstChild.nodeValue;
                    sBirth = oMember.getElementsByTagName("birth")[0].firstChild.nodeValue;
                    sConstell = oMember.getElementsByTagName("constell")[0].firstChild.nodeValue;
                    sMobile = oMember.getElementsByTagName("mobile")[0].firstChild.nodeValue;
                    //添加一行
                    addTableRow(sName, sClass, sBirth, sConstell, sMobile);
                }
            }

其中addTableRow()函数将拆分出来的每一组XML数据组装成表格<table>的一行,添加到页面中。代码如下:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wfypdj.html