将响应解析为XML

2017-06-23 15:20:00
admin
原创
413
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>利用DOM处理XML响应文档</title>
    
<script type="text/javascript">
var xmlHttpObject;
var requestType = "";
 
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    else if (window.XMLHttpRequest) {
        xmlHttpObject = new XMLHttpRequest();
    }
}
    
function launchRequest(requestedList) {
    requestType = requestedList;
    createXMLHttpRequest();
    xmlHttpObject.onreadystatechange = handleStateChange;
    xmlHttpObject.open("GET", "http://code.ybao.org/demo/src/parseXML.xml", true);
    xmlHttpObject.send(null);
}
    
function handleStateChange() {
    if(xmlHttpObject.readyState == 4) {
        if(xmlHttpObject.status == 200) {
            if(requestType == "EC") {
                listEastOfChinaProvinces();
            }
            else if(requestType == "ALL") {
                listAllProvinces();
            }
        }
    }
}
 
function listEastOfChinaProvinces() {
    var xmlDoc = xmlHttpObject.responseXML;
    var ECNode = xmlDoc.getElementsByTagName("华东地区")[0];
    
    var out = "华东地区";
    var EastOfChinaProvinces = ECNode.getElementsByTagName("省市");
    
    outputList("华东地区", EastOfChinaProvinces);
}
 
function listAllProvinces() {
    var xmlDoc = xmlHttpObject.responseXML;
    var allProvinces = xmlDoc.getElementsByTagName("省市");
    
    outputList("所有省市", allProvinces);
}
 
function outputList(title, Provinces) {
    var out = title;
    var currentProvince= null;
    for(var i = 0; i < Provinces.length; i++) {
        currentProvince = Provinces[i];
        out = out + "\n- " + currentProvince.childNodes[0].nodeValue;
    }
    
    alert(out);
}
</script>
</head>
 
<body>
    <h1>处理"中国大陆省市"的XML文档</h1>
    <br/><br/>
    <form action="#">
        <input type="button" value="查看中国大陆所有省市" onclick="launchRequest('ALL');"/>
        <br/><br/>
        <input type="button" value="查看华东地区所有省市" onclick="launchRequest('EC');"/>
    </form>
</body>
</html>
文章分类
联系我们
电话: 18902328227
Email: 2689701946@qq.com
QQ: 2689701946
微信: 18902328227
地址: 广州番禺区繁华路
  • 在线客服
  • 关注微信
  • 联系电话
    • 欢迎咨询
    • 欢迎加入QQ群 303257430
  • 公众号:源宝网络
    • 联系电话及微信号 18902328227