开发者问题收集

jQuery:处理多个 JSON 数据

2016-01-05
53

我的代码:

$.ajax({
    url: 'online.php',
    success: function(data) {
        var userOnline = $.parseJSON(data);
        $('#usersOnline').append($('<div id="usersOnlineUser">').text(userOnline['username']).append($('<span class="badge">').text('aktiv')));
    }
});

JSON:

{"username":"Aarivex","active":"1"}

它工作正常。但我如何处理多个 JSON 数据,如

{"username":"Aarivex","active":"1"}{"username":"Aarivex2","active":"1"}

1个回答

如果我们假设您的数据是:

var data = [{"username":"Aarivex","active":"1"}, {"username":"Aarivex2","active":"1"}];

您的成功函数变为:

success: function(data) {
   $.each(data, function(index, element) {
      $('#usersOnline').append($('').text(element['username']).append($('').text('aktiv')));
   });
}
gaetanoM
2016-01-05