从JSON填充选择列表

时间:2015-02-05 18:55:36

标签: jquery json select

我收到一些JSON数据如下:

{
"COLUMNS": [
    "COMP_ID",
    "COMP_NAME",
    "FIRST_NAME",
    "LAST_NAME",
    "EMAIL_ADDRESS"
],
"DATA": [
    [
        68,
        "Comp Name 1",
        "Nicole ",
        "Lastname ",
        "a@a.com"
    ],
    [
        173,
        "Comp Name 2",
        "Megan",
        "Lastname ",
        "b@a.com "
    ],
    [
        175,
        "Comp Name 3",
        "Elizabeth ",
        "Lastname ",
        "c@a.com "
    ],
    [
        244,
        "Comp Name 4",
        "Kelly ",
        "Lastname ",
        "d@a.com "
    ],
    [
        266,
        "Comp Name 5",
        "Andrea ",
        "Lastname ",
        "e@a.com "
    ]
]
}

我正在尝试从结果集中创建一个选择列表。它应该是:

  <select name="selectCompany" id="selectCompany">
    <option value="68">Comp Name 1</option>
    <option value="173">Comp Name 2</option>
    <option value="175">Comp Name 3</option>
    <option value="244">Comp Name 4</option>
    <option value="266">Comp Name 5</option>
 </select>

在我的ajax电话中,我正在使用:

 success: function (result) {
     var compData = $.parseJSON(result);
     $('#selectCompany').attr('enabled', 'true');
     $.each(compData, function() {
        $('#selectCompany').append(
            $("<option></option>").text($.trim(compData.DATA[0][0])).val($.trim(compData.DATA[0][1]))
                                    );
                                });
                            },

如何正确循环数据并填充选择?

2 个答案:

答案 0 :(得分:2)

JSFIDDLE DEMO - &gt; http://jsfiddle.net/wqzuxdpy/

使用.each()

与compData.DATA迭代
$.each(compData.DATA, function () {
    var $option = $('<option/>').text(this[1]).val(this[0]);
    $('#selectCompany').append($option);
});

答案 1 :(得分:0)

试试这个

    success: function (result) {
    var compData = $.parseJSON(result);
    $('#selectCompany').attr('enabled', 'true');
         var opts = ""
         $.each(compData, function() {
             opts.concat("<option value='"+$.trim(compData.DATA[0[0])+"'>"+$.trim(compData.DATA[0][1])+"</option>"
         });
    $('#selectCompany').append(opts);
},