XML到动态选择菜单(使用AJAX)

时间:2010-02-25 12:06:25

标签: javascript xml ajax dom

我是AJAX和XML的新手。我被困在学校作业.. 任务是处理一个XML文件,该文件由2000个不同的地方组成,包括姓名,城市名称和县名。并使用不同的县制作一个下拉菜单,但只有一次。

XML文件如下所示:

<places>
 <place>
  <Name>Vestby</Name>
  <City>Vestby</City>
  <County>Akershus</County>
 </place> 
...
 <place>
  <Name>Eidsbugarden</Name>
  <City>Vang</City>
  <County>Oppland</County>
 </place>
</places>

我的功能如下:

function fillElementWithCounty(){
 var selectElement = document.getElementById("selectMenu");
 var allPlaces = countyXHRobject.responseXML.getElementsByTagName("place");
 var prevCounty = "";

 selectElement.options[0] = new Option("Choose county...", "chooseCounty", true, false);
 for (teller=1; teller < allPlaces.length; teller++){
  var county = allPlaces[teller].getElementsByTagName("county")[0].firstChild.nodeValue;
   if (county ! = prevCounty ) {
    selectElement.options[teller]  = new Option(county, county, false, false);
   }
   prevCounty = county;
 }
}

此功能显示每个县一次,但它也显示所有“空白”县。 我做错了什么?

调用fillElementWithCounty()的函数如下所示:

function showPlaces(){
 countyXHRobject = lagXHRobjekt();
 if (countyXHRobject) {
  countyXHRobject.onreadystatechange = function() {
   if (countyXHRobject.readyState = = 4) {
    fillElementWithCounty();
   }
  }
  countyXHRobject.open("GET", "viktigestader.xml");
  countyXHRobject.send(null);
 }
}

1 个答案:

答案 0 :(得分:-1)

我有这个工作:

function fillElementWithCounty(){
    var selectElement = document.getElementById("selectMenu");
    var allPlaces = countyXHRobject.responseXML.getElementsByTagName("place");
    var x = countyXHRobject.responseXML;
    var prevCounty = "";

    selectElement.options[0] = new Option("Select county...", "selectcounty", true, false);
    j = 1;
    for (i=1; i < allPlaces.length; i++){
        var county = allPlaces[i].getElementsByTagName("county")[0].firstChild.nodeValue;
        if (county != prevCounty) {
            selectElement.options[j] = new Option(county, county, false, false);
            j++;
        }
        prevCounty = county;
    }
}