2011-05-12 105 views
0

這是我第一次以任何方式使用ajax,請耐心等待。需要幫助通過javascript腳本循環瀏覽xml文件

在我的程序中,我有一個下拉框,根據所選的狀態動態地提取郵政編碼,縣和城市。到目前爲止,各縣工作正常,但郵政編碼和城市只顯示我的XML表單上的第一條記錄。

的XML看起來是這樣的:

<states> 
    <counties> 
    <county> 
     <countyid>id#1</countyid> 
     <countyname>nassau</countyname> 
    </county> 
    </counties> 
    <zipcodes> 
    <zip>10109</zip> 
    </zipcodes> 
    <cities> 
    <city>New York</city> 
    <cities> 
</states> 

現在,通過縣部分循環的JavaScript看起來像這樣:

target1.options[0] = new Option("Select County", "null"); 
for (var i = 0; i < xmlCounties.length; i++) { 
target1.options[target1.options.length] = new Option(xmlCounties[i].childNodes[1].firstChild.nodeValue, xmlCounties[i].childNodes[0].firstChild.nodeValue, false, (matched == xmlCounties[i].childNodes[0].firstChild.nodeValue)); 

}

這工作得很好,但對於城市和郵政編碼他們沒有,它們都是這樣的,並且與上述示例相同:

target2.options[0] = new Option("Select Zipcode", "null"); 
for (var i = 0; i < xmlZips.length; i++) {target2.options[target2.options.length] = new Option(xmlZips[i].childNodes[0].firstChild.nodeValue, xmlZips[i].childNodes[0].firstChild.nodeValue, false, (matched == xmlZips[i].childNodes[0].firstChild.nodeValue)); 
} 

它們都從xml中提取數據,但只是第一條記錄。任何想法如何得到這個固定?謝謝!

+0

你使用哪個JavaScript庫(如果有的話)? – jimbojw 2011-05-12 19:31:16

+0

我沒有使用任何庫,只是直起來的JavaScript。 – rshivers 2011-05-12 19:39:10

回答

0

縣是2級深..拉鍊和城市只有一個層次深。那就是原因。試試這個

target2.options[0] = new Option("Select Zipcode", "null"); 
for (var i = 0; i < xmlZips.length; i++) {target2.options[target2.options.length] = new Option(xmlZips[i].childNodes[0].nodeValue, xmlZips[i].childNodes[0].nodeValue, false, (matched == xmlZips[i].childNodes[0].nodeValue)); 
} 
+0

我不認爲這是因爲我在我的XML中爲郵政編碼和城市獲取第一條記錄,它只是沒有循環並拉動所有的結果。我試過你的建議,它只是拉空值。我很欣賞這個建議,謝謝。 – rshivers 2011-05-12 19:52:48