2010-02-25 34 views
0

我是AJAX和XML的新手。我被困在一個學校任務中​​。 任務是處理一個由2000個不同名稱,城市名稱和縣名稱組成的XML文件。並用不同的縣製作下拉菜單,但只有一次。XML到動態選擇菜單(使用AJAX)

的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

我得到這個工作:

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; 
    } 
}