简体   繁体   中英

jQuery getJSON not populating HTML select properly

I have an HTML <select> :

<div id="content">
    <input type="button" id="get-btn" onclick="getData();"/>
    <select id="attrib-type-sel"></select>
</div>

When the user clicks the following button, I want to use jQuery's getJSON method to hit my server, pull back data, and populate the <select> with options:

$(document).ready(function() {
    $.getJSON(
        "some/url/on/my/server",
        function(data) {
        var optionsHTML = "";
        var len = data.length;
        for(var i = 0; i < len; i++) {
            optionsHTML += '<option value="' + data[i] + '">'
                + data[i] + '</option>';
        }

        $('#attrib-type-sel').html(optionsHTML);
    });
});

When I run this code, in Firebug, I see that the AJAX call is successful and returns the following JSON:

[
    {
        "id":1,
        "name":"Snoopy",
        "tag":"SNOOPY",
        "allowsAll":false
    }
]

(Only returns 1 record).

However, when back in the UI, when this code fires it creates a <select> that has 1 options whose inner HTML reads [object Object] .

Can anyone spot what is going on here? It looks like my getJSON is OK, but the code to extract the JSON from the results and use it to populate my select is buggy. Thanks in advance!

it's because that data[i] is an object. Try using console.log(data[i]) to check out what it's looking like.

data[i].id and data[i].name are likely what you are looking for.

you need data[i].id & data[i].name to construct your options.

for(var i = 0; i < len; i++) {
        optionsHTML += '<option value="' + data[i].id + '">'
            + data[i].name + '</option>';
}

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