当前位置: 代码迷 >> JavaScript >> 没法加载xml文档
  详细解决方案

没法加载xml文档

热度:121   发布时间:2012-07-25 09:43:05.0
无法加载xml文档
city.html
JScript code
<!DOCTYPE html>
<html>
  <head>
    <title>city.html</title>
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <select id="province" name="province">
        <option value="">请选择……</option>
        <option value="山东">山东</option>
        <option value="河南">河南</option>
        <option value="河北">河北</option>
    </select>
    
    <select id="city" name="city">
        <option value="">请选择……</option>
    </select>
  </body>
<script type="text/javascript">
    window.onload = function(){
        document.getElementById("province").onchange = function(){
            alert("aaa");
            //测试xml文档是否加载成功
            var xmlDoc = parseXML("cities.xml");
            var provinceElements = xmlDoc.getElementsByTagName("province");
            alert(provinceElements.length);
        }
    }
    
    /**
     *加载xml文档
     */
    function parseXML(filename) {

        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("GET", filename, false);
        xmlhttp.send();
        xmlDoc = xmlhttp.responseXML;

    }
</script>
</html>



cities.xml
XML code
<?xml version="1.0" encoding="UTF-8"?>
<china>
    <province name='山东'>
        <city>济南</city>
        <city>菏泽</city>
        <city>青岛</city>
        <city>大连</city>
    </province>
    <province name='河南'>
        <city>郑州</city>
        <city>许昌</city>
        <city>洛阳</city>
        <city>开封</city>
    </province>
    <province name='河北'>
        <city>保定</city>
        <city>石家庄</city>
        <city>秦皇岛</city>
    </province>
</china>


运行的时候,只能弹出“aaa”的提示框,无法弹出alert(provinceElements.length);的提示框

请高手看看我那里出了问题:
注:city.html和cities.xml在同一个目录下

------解决方案--------------------
xmlDoc.getElementsByTagName("province");
你这是要取xml里面有几个province节点还是页面上
<select id="province" name="province">
<option value="">请选择……</option>
<option value="山东">山东</option>
<option value="河南">河南</option>
<option value="河北">河北</option>
</select>
有几个选项啊?
取xml里面节点的话就把
xmlDoc = xmlhttp.responseXML;
改为
var xmlDoc = xmlhttp.responseXML;
return xmlDoc
我测试了弹出长度为3是在ie9下
  相关解决方案