ajax对xml的信息接收与发送

前端之家收集整理的这篇文章主要介绍了ajax对xml的信息接收与发送前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

xml文件

<?xml version="1.0" encoding="utf-8" ?>
<students>
    <student>
        <name>dancheng</name>
        <age>21</age>
        <addr>长春</addr>
    </student>
    <student>
        <name>dancheng1</name>
        <age>22</age>
        <addr>白城</addr>
    </student>
    <student>
        <name>dancheng2</name>
        <age>23</age>
        <addr>通榆</addr>
    </student>
</students>

JavaScript操作文件

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function f1() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4){
                    //alert(xhr.responseText);   //返回字符串
                    //alert(xhr.responseXML);    //返回文档对象
                    var xmldom = xhr.responseXML;
                    //console.log(xmldom.firstChild);
                    //console.log(xmldom.firstChild.childNodes);
                    var stu = xmldom.getElementsByTagName('student');
                    var dv = document.getElementById('dv');
                    var s = "";
                    for(var i = 0; i < stu.length; i++){
                        var username = stu[i].getElementsByTagName('name')[0].innerHTML;
                        var userage = stu[i].getElementsByTagName('age')[0].innerHTML;
                        var useraddr = stu[i].getElementsByTagName('addr')[0].innerHTML;
                        s += "名称:" + username + "--年龄:" + userage + "--地址:" + useraddr + "<br/>";
                    }
                    document.getElementById('dv').innerHTML += s;
                }
            }
            xhr.open('get','./08-xml.xml');
            xhr.send(null);
        }
    </script>
</head>
<body>
    <h2>ajax+JavaScript实现对xml的处理</h2>
    <input type="button" value="处理" onclick="f1()" />
    <div id="dv"></div>
</body>
</html>
效果图:

猜你在找的Ajax相关文章