create drop down dynamically from xml

2019-05-18 18:43发布

问题:

I have today problem with creating drop-down lists:

I have xml file like with such structure like this:

<resultset>
  <row>
    <field name="iso3166_2">AF</field>
    <field name="country">AFGHANISTAN</field>
    <field name="fixed">1.000</field>
    <field name="mobile">1.300</field>
  </row>
  <row>
    <field name="iso3166_2">US</field>
    <field name="country">ALASKA</field>
    <field name="fixed">0.100</field>
    <field name="mobile">0.100</field>
  </row>
</resultset>

And I would like to create drop-down list with country names in it (taken from those fields: <field name="country">...</field>).

In addtion, after choosing country from this drop-down I would like to show variables from fixed and mobile from the same row set as chosen country in such span's:

<span id="mobile"><!-- mobile value --></span> and in <span id="fixed"><!-- fixed value --></span>

I hope it is clear what I want to achieve, I was trying to solve it with answers from similiar question: dynamic load data from xml to drop down box with jquery but it's not working for me (I was doing something wrong I suppose). Please help!

回答1:

Something like this should work:

$.ajax({
    url: 'img/test.xml',
    dataType: 'xml', // Make sure it knows to treat it as XML
    success: function(xml) {
        var rows = xml.childNodes[0].getElementsByTagName("row"),
            // This assumes your <select> has id of "countries"
            $dropdown = $("#countries");

        $(rows).each(function(index, row) {
            var fields = row.getElementsByTagName("field"),
                $option = $(document.createElement("option"));

            $(fields).each(function(index, field) {
                var name = field.getAttribute("name"),
                    // A special way to get the text contents of an XML node
                    value = $(field).contents()[0].wholeText;

                // If it's the "country" field, just stick it in the option
                if (name == "country") {
                    $option.text(value);
                } else {
                    // If it's anything else, store it as extra data
                    $option.data(name, value);
                }
            });

            $dropdown.append($option);
        });

        // Whenever you change which option is selected
        $dropdown.change(function() {
            $option = $dropdown.find(":selected");

            // Fill in the spans using the extra data you saved
            $("#fixed").text($option.data("fixed"));
            $("#mobile").text($option.data("mobile"));
        });
    }
});

In short, if you pull in your XML through AJAX, make sure it's treated as XML then you can treat it just like it's any other kind of document (with some caveats). Clearly this could be done with vanilla JavaScript but I find it easier to do with jQuery.