0

我怎样才能把这个嵌套数组变成一个漂亮的 html 列表?

<ul id="droppable">
    <li value="id">lastname firstname</li>
    <li value="id">lastname firstname</li>
</ul>

这个数组是我从我的 ajaxrequest 中得到的:

[{
    "id": 87,
    "lastname": "BOUSSAUW",
    "firstname": "ANNEMIE"
}, {
    "id": 88,
    "lastname": "VEREENOOGHE",
    "firstname": "STEFAAN"
}, {
    "id": 89,
    "lastname": "VERHEYDEN",
    "firstname": "JOKE"
}]

我的ajax请求:

$.ajax({
    type: 'GET',
    url: 'PHPCalls.php?CallID=GetGroupMembersJSON',
    data: { GroupID : str },
    success: function(data){
        var html = '';
        $.each(data, function(i, obj) {
            html += '<li id="' + obj.id + '">' + obj.lastname + ' ' + obj.firstname + '</li>';
        });

        $('#droppable').html(html);
    }
});

编辑: ul-tag 已经存在。无需添加但我没有提及

我得到的结果是一长串:

<li id="undefined">
    undefined undefined
</li>
4

1 回答 1

3

您必须解析 JSON,然后遍历数组。

var json = '[{"id": 87,"lastname": "BOUSSAUW","firstname": "ANNEMIE"}, {"id": 88,"lastname": "VEREENOOGHE","firstname": "STEFAAN"}, {"id": 89,"lastname": "VERHEYDEN","firstname": "JOKE"}]';
var data = $.parseJSON(json);

$('#form').html('');

$.each(data, function(i, o) {
    $('#form').append('<li id="'+o.id+'">'+o.lastname+' '+o.firstname+'</li>');
});

http://jsfiddle.net/Recode/mDHfs/1/

于 2013-09-14T19:43:34.363 回答