简体   繁体   English

jQuery getJSON无法正确填充HTML选择

[英]jQuery getJSON not populating HTML select properly

I have an HTML <select> : 我有一个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: 当用户单击以下按钮时,我想使用jQuery的getJSON方法来命中服务器,拉回数据,并使用选项填充<select>

$(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: 在Firebug中运行此代码时,我看到AJAX调用成功,并返回以下JSON:

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

(Only returns 1 record). (仅返回1条记录)。

However, when back in the UI, when this code fires it creates a <select> that has 1 options whose inner HTML reads [object Object] . 但是,当返回UI时,此代码触发时,它会创建一个具有1个选项的<select> ,其内部HTML读取[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. 看来我的getJSON可以,但是从结果中提取JSON并使用它填充我的选择的代码有很多问题。 Thanks in advance! 提前致谢!

it's because that data[i] is an object. 这是因为data [i]是一个对象。 Try using console.log(data[i]) to check out what it's looking like. 尝试使用console.log(data[i])来查看它的外观。

data[i].id and data[i].name are likely what you are looking for. 您可能正在寻找data[i].iddata[i].name

you need data[i].id & data[i].name to construct your options. 您需要data[i].iddata[i].name来构造您的选项。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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