[英]How to populate dropdown list from an external xml file using javascript
I've a javascript running which reads an xml file and populates the options for a dropdown list.我有一个 javascript 正在运行,它读取 xml 文件并填充下拉列表的选项。
Here is the javascript:这是 javascript:
var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest; } /*else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); //code for IE6, IE5 }*/ xhr.open('GET','metaFiles/searchPage/js/docType.xml',true); xhr.send(); window.onload = function() { var x, xmldoc; xmldoc = xhr.responseXML; x = xmldoc.getElementsByTagName("DocTypes"); var select1 = document.getElementById("doctype"); var option = document.createElement('option'); option.text = "Select Document Type"; option.value = "empty"; select1.add(option); var option2; //document.write(x.length); for (var i = 0; i <x.length; i++) { option2 = document.createElement('option'); option2.text = x[i].getElementsByTagName("doctype")[0].childNodes[0].nodeValue; option2.value = x[i]; select1.add(option2); } return xhr; }
Here is the xml file:这是 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<DocTypes>
<doctype>Change Record</doctype>
<doctype>Form</doctype>
<doctype>Master Batch Record</doctype>
<doctype>Method</doctype>
<doctype>Policy</doctype>
<doctype>Procedure</doctype>
</DocTypes>
</root>
Here is my html part:这是我的 html 零件:
<select id="doctype" name="doctype" class="domain">
The issue is only one item from the doctype is getting populated in the dropdown.问题是下拉菜单中只有 doctype 中的一项被填充。 Only the Change Record is getting populated.
只有更改记录被填充。 Any idea what is causing the issue?
知道是什么导致了这个问题吗? I've also checked the x.length value and it is 1. Not sure why is only picking the first one.
我还检查了 x.length 值,它是 1。不知道为什么只选择第一个。
I figured it out that the issue was with my xml file.我发现问题出在我的 xml 文件上。
Updated xml file:更新了 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Sites>
<owngsite>Change Record</owngsite>
</Sites>
<DocTypes>
<doctype>Form</doctype>
</DocTypes>
<Sites>
<owngsite>Master Batch Record</owngsite>
</Sites>
<Sites>
<owngsite>Method</owngsite>
</Sites>
<Sites>
<owngsite>Policy</owngsite>
</Sites>
<Sites>
<owngsite>Procedure</owngsite>
</Sites>
</root>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.