使用jQuery将JSON数据转换为DOM

时间:2017-06-28 11:29:19

标签: javascript jquery html json dom

我希望将每个'item'(来自JSON)转换为出现在一个部分(或div)中,其中图像及其链接显示为name,id和price - 如何使用jQuery完成此操作。 jQuery和JSON在下面,我目前没有HTML中的任何类,除了标题的“placements-title”和该部分的“placements-items”。

当前的jQuery:

$.ajax({
  type: 'GET',
  url: 'pathtoJSONdata.json',
  dataType: 'json',
  success: function (data) {
     $(".placements-title h2").append(data.placements[0].message);
     $(".placements-items").append(data.placements[0].items[1].id);


  }
});

1 个答案:

答案 0 :(得分:2)

使用循环将html构建为字符串并将其附加到所需的dom元素

var data = {
  "placements": [{
    "message": "If you like this, you might be into these",
    "items": [{
        "id": "029148",
        "name": "Woodblock Play Suit",
        "linkURL": "http://www.warehouse.co.uk/gb/just-arrived/all/woodblock-play-suit/029148.html",
        "imageURL": "http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw0f93fcd4/images/hi-res/warehouse_02914899_2.jpg",
        "price": "46.00"
      },
      {
        "id": "0294526806",
        "name": "Smock Dress",
        "linkURL": "http://www.warehouse.co.uk/gb/just-arrived/all/smock-dress/0294526806.html",
        "imageURL": "http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dwc9d5ea05/images/hi-res/warehouse_02945268_5.jpg",
        "price": "39.00"
      },
      {
        "id": "0297180006",
        "name": "Cami",
        "linkURL": "http://www.warehouse.co.uk/gb/just-arrived/all/cami/0297180006.html",
        "imageURL": "http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw4b954022/images/hi-res/warehouse_02971800_2.jpg",
        "price": "9.00"
      },
      {
        "id": "0298473606",
        "name": "Asymmetric Wrap Cami Dress",
        "imageURL": "http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw686fea84/images/hi-res/warehouse_02984736_2.jpg",
        "price": "46.00"
      },
      {
        "id": "0297155306",
        "name": "Casual Stripe Tee",
        "linkURL": "http://www.warehouse.co.uk/gb/just-arrived/all/casual-stripe-tee/0297155306.html",
        "imageURL": "http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw4609af3e/images/hi-res/warehouse_02971553_2.jpg",
        "price": "16.00"
      }
    ]
  }]
}
$.each(data.placements[0].items,function(i,v){
$('body').append('<img src="'+v.imageURL+'" height="50" width="50"><div class="placements-title"><a href="'+v.linkURL+'"><h2>'+v.name+'</h2>'+v.price+'</div>')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>