通过Ajax / jQuery检索更复杂的JSON

时间:2014-03-19 13:17:30

标签: jquery ajax json jsonp

我正在尝试通过AJAX从JSON接收数据,但JSON结构更复杂,而不仅仅是一个值/键。

这是我遇到的代码:

$.ajax('data.json', {
    crossDomain: true,
    dataType: "json",
    success: function(data, text, xhqr) {
      $.each(data, function(i, item) {
      console.log(data.Cars);
      $("body").html(data.Cars)
    });
 }
});

JSON:

{
   "extracted" : "2014-03-18 13:00:12",
   "LastRun" : "2014-03-18 13:00:00",
   "Cars" : {
      "Audi" : {
         "Total" : "18",
         "Type" : "Sport",
         "features" : {
            "Airbag" : "yes",
            "Radio" : "No",
            "Convertible" : "yes"
         }
      },
      "Ford" : {
         "Total" : "109",
         "Type" : "Sport",
         "features" : {
            "Airbag" : "yes",
            "Radio" : "No",
            "Convertible" : "no"
         }
      },
      "Mercedes" : {
         "Total" : "60",
         "Type" : "Luxury",
         "features" : {
            "Airbag" : "No",
            "Radio" : "Yes",
            "Convertible" : "yes"
         }
      }
   }
}

理想情况下,我希望数据以此表格格式显示: enter image description here

有人可以帮助我,请问如何接收或阅读json值/键? 非常感谢

1 个答案:

答案 0 :(得分:0)

$.ajax({
    url: 'data.json',
    crossDomain: true,
    dataType: "json"
}).done(function(data) {
    var table = $('<table />'),
        thead = $('<thead />'),
        tbody = $('<tbody />');

    thead.append(
        $('<tr />').append(
            $('<th />', {text: 'Car'}),
            $('<th />', {text: 'Type'}),
            $('<th />', {text: 'Airbag'}),
            $('<th />', {text: 'Radio'}),
            $('<th />', {text: 'Convertible'}),
            $('<th />', {text: 'Total'})
        )
    );

    $.each(data.Cars, function(car, specs) {
        tbody.append(
            $('<tr />').append(
                $('<td />', {text: car}),
                $('<td />', {text: specs.Type}),
                $('<td />', {text: specs.features.Airbag}),
                $('<td />', {text: specs.features.Radio}),
                $('<td />', {text: specs.features.Convertible}),
                $('<td />', {text: specs.Total})
            )
        );
    });

    $('body').append( table.append(thead, tbody) );
});

FIDDLE