大家好,
我读取 xml 的代码有问题。我使用 ajax 读取 xml 数据并将其填充到组合框中。我的问题是它只读取了第一个数据。这是我的代码
我的xml是这样的
<info>
<area>
<code>1</code>
<name>area1</name>
</area>
<area>
<code>2</code>
<name>area2</name>
</area>
</info>
和我的javascript
if(http.readyState == 4 && http.status == 200) {
//get select elements
var item = document.ProblemMaintenanceForm.elements["probArea"];
//empty combobox
item.options.length = 0;
//read xml data from action file
var test = http.responseXML.getElementsByTagName("area");
alert(test.length);
for ( var i=0; i < test.length; i++ ){
var tests = test[i];
item.options[item.options.length] = new Option(tests.getElementsByTagName("name")[i].childNodes[0].nodeValue,tests.getElementsByTagName("code")[i].childNodes[0].nodeValue);
}
}
最佳答案
您不必为它编制索引两次。只需将该行更改为:
item.options[item.options.length] = new Option(
tests.getElementsByTagName("name")[0].childNodes[0].nodeValue,
tests.getElementsByTagName("code")[0].childNodes[0].nodeValue
);
因此,为清楚起见,您的上述代码块应如下所示:
if(http.readyState == 4 && http.status == 200) {
//get select elements
var item = document.ProblemMaintenanceForm.elements["probArea"];
//empty combobox
item.options.length = 0;
//read xml data from action file
var test = http.responseXML.getElementsByTagName("area");
alert(test.length);
for ( var i=0; i < test.length; i++ ){
var tests = test[i];
item.options[item.options.length] = new Option(
tests.getElementsByTagName("name")[0].childNodes[0].nodeValue,
tests.getElementsByTagName("code")[0].childNodes[0].nodeValue
);
}
}
关于javascript - 在javascript问题中读取xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2838760/