[未解决]Ajax-读取并解析XML,动态生成select下拉列表框

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <title>www.mldnjava.cn,MLDN高端Java培训</title>

    <script language="javascript">

        var xmlHttp ;

        function createXMLHttp(){

            if(window.ActiveXObject){

                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") ;

            } else {

                xmlHttp = new XMLHttpRequest() ;

            }

        }

        function getCity(){

            createXMLHttp() ;

            xmlHttp.open("POST","allarea.xml") ;

            xmlHttp.onreadystatechange = getCityCallback ;

            xmlHttp.send(null) ;

        }

        function getCityCallback(){

            if(xmlHttp.readyState == 4){

                if(xmlHttp.status == 200){

                    var allarea = xmlHttp.responseXML.getElementsByTagName("allarea")[0].childNodes ;    // 取得全部的allarea下的节点

                    var select = document.getElementById("city") ;

                    select.length = 1 ;    // 每次选择一个

                    select.options[0].selected = true ;    // 第一个为选中的状态

                    for(var i=0;i<allarea.length;i++){

                        var area = allarea[i] ;

                        var option = document.createElement("option") ;

                        var id = area.getElementsByTagName("id")[0].firstChild.nodeValue ;

                        var title = area.getElementsByTagName("title")[0].firstChild.nodeValue;

                        option.setAttribute("value",id) ;

                        option.appendChild(document.createTextNode(title)) ;

                        select.appendChild(option) ;

                    }

                }

            }

        }

    </script>

</head>

<body onload="getCity()">

    <form action="" method="post">

        请选择喜欢的城市:

            <select id="city">

                <option value="0"> - 请选择城市 -</option>

            </select>

    </form>

</body>

</html>

但是有个问题,就是,如果我把其中的

function createXMLHttp

换成如下实现,就会出错:

        function createXMLHttp(){

            if(window.XMLHttpRequest){

                xmlHttp = new XMLHttpRequest() ;

            } else {

                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") ;

            }

        }

症状就是读取不了allarea.xml

<?xml version="1.0" encoding="UTF-8"?>

<allarea>

    <area>

        <id>1</id>

        <title>北京</title>

    </area>

    <area>

        <id>2</id>

        <title>天津</title>

    </area>

    <area>

        <id>3</id>

        <title>南京</title>

    </area>

</allarea>

到目前为止,我对Ajax的理解仍浮于表面,先把问题放在这里,到了合适的时机再来解决。

参考了这篇blog:http://www.cnblogs.com/fullhouse/archive/2012/01/17/2324849.html

你可能感兴趣的:(select)