hai all,
i have a problem with my code to read the xml.I have use ajax to read xml data and populate it in combobox. My problem is it only read the first data.Here is my code
my xml like this
<info>
<area>
<code>1</code>
<name>area1</name>
</area>
<area>
<code>2</code>
<name>area2</name>
</area>
</info>
and my 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++ )开发者_C百科{
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);
}
}
You don't have to index it twice. Just change that line to:
item.options[item.options.length] = new Option(
tests.getElementsByTagName("name")[0].childNodes[0].nodeValue,
tests.getElementsByTagName("code")[0].childNodes[0].nodeValue
);
So, for clarity your above code block should look like:
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
);
}
}
You either need another loop or a fixed index instead of reusing the loop index (e.g. ...("name")[i]
) in the following line:
item.options[item.options.length] = new Option(
tests.getElementsByTagName("name")[i].childNodes[0].nodeValue,
tests.getElementsByTagName("code")[i].childNodes[0].nodeValue
);
You are looping through the element nodes using the var i
which obviously will get incremented by one every instance of the loop. Now, if you parse any element at i > 0
you won't be able to access the name
tag as there is none present (at least in your example xml).
精彩评论