![](/img/trans.png)
[英]Ajax call for dynamic menu works for first <select> element, but not additional ones
[英]XML to dynamic select menu (with AJAX)
我是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);
}
}
我得到了这个工作:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.