简体   繁体   中英

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.

Here is the 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 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:

<select id="doctype" name="doctype" class="domain">
                    

The issue is only one item from the doctype is getting populated in the dropdown. 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.

I figured it out that the issue was with my xml file.

Updated xml file:

<?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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM