JSON Data to UL


JSON Data to UL

我正在从ajax获取json数据,我认为我即将完成这项工作,但由于某种原因,我的UL没有填充,我找不到任何调试信息来帮助我。

有人能给我指正确的方向吗?

json data : 
{"data":[{"racer_id":73,"racing_nbr":"4","entry_id":131},
{"racer_id":9,"racing_nbr":"48","entry_id":132},
{"racer_id":525,"racing_nbr":"7","entry_id":133},
{"racer_id":534,"racing_nbr":"11","entry_id":134},
{"racer_id":213,"racing_nbr":"72","entry_id":135},
{"racer_id":574,"racing_nbr":"66f","entry_id":136}]}

$('.list-group-item').click(function() {
var data = 'class_id='+ $(this).attr('rel') + '&event_id=' +<?php echo $_GET['event_id']; ?>
// POST to server using $.post or $.ajax
$.ajax({
    data: data,
    type: 'GET',
    dataType: 'JSON',
    url: 'php/builder/getRidersScoringHeats.php',
    success: function(data) {
      var obj = data,  // get entry object (array) from JSON data
      ul = $("#sortable");                    // create a new ul element
        // iterate over the array and build the list
          for (var i = 0, l = obj.length; i < l; ++i) {
            ul.append("<li class='ui-state-default' id='item-" + obj[i].entry_id + "'>" + obj[i].racing_nbr + " - " + obj[i].racer_id + "</li>");
          }
      $("#sortable").append(ul);    // add the list to the DOM
  }
 });
});

如有任何帮助,我们将不胜感激。

提前谢谢。

在您的案例中,data实际上包含一个名为data的对象,它是objects的数组集合。

因此,要轻松做到这一点:

$.each(data.data, function(i, info){
    ul.append("<li class='ui-state-default' id='item-" + info.entry_id + "'>" + info.racing_nbr + " - " + info.racer_id + "</li>");
});

如果data是一个分配给obj的对象,那么问题是obj.length没有解析为任何值。对象没有length属性。您需要将数据放在顶级的数组中,或者使用underscore.js这样的库来实现这一点。

或者,请参阅以下答案:JavaScript对象的长度