getJSON - 追加Images数组

时间:2016-02-08 10:56:54

标签: javascript jquery json

我想通过Ajax请求显示JSON文件中的数据。我显示除图像数组之外的每个数据值。我哪里错了? 这是JSON:

{
"item": {
    "name": "ABITO CORTO",
    "details": "Maglia leggera, Collo a V, Interno semi-foderato, Logo.",
    "composition": "Composizione: 94% Viscosa, 6% Elastam.",
    "modelDetails": [
        "La modella indossa una taglia 40",
        "Misure: 86 - 60 - 90",
        "Altezza modella: 178cm"
    ],
    "images": [
        "http://cdn.yoox.biz/34/34295573it_12n_f.jpg",
        "http://cdn.yoox.biz/34/34295573it_12n_r.jpg",
        "http://cdn.yoox.biz/34/34295573it_12n_e.jpg",
        "http://cdn.yoox.biz/34/34295573it_12n_d.jpg"
              ]
       }
}

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>

  <button id="driver">ONE</button>
  <div class="news_details_container">
  <img src="" alt="" >
  </div>

  </body>
  </html>

SCRIPT:

$("#driver").click( function() {
            $.getJSON( "assets/data/one.json", function(data) { 
            $.each(data, function(key, value) { 
            $(".news_details_container").append(value.name);
            $(".news_details_container").append(value.details);
            $(".news_details_container").append(value.coposition );
            $(".news_details_container").append(value.modelDetails);
            $(".news_details_container").append('<img src="' + value.images + '" />'); 
           });
     });
});

我是Ajax + JSON的新手。谁能帮我? 感谢。

2 个答案:

答案 0 :(得分:0)

你有一个img src数组,你需要一个循环来显示所有

尝试:

    $("#driver").click( function() {
           $.getJSON( "assets/data/one.json", function(data) { 
              $.each(data, function(key, value) { 
                $(".news_details_container").append(value.name);
                $(".news_details_container").append(value.details);
                $(".news_details_container").append(value.coposition );
                $(".news_details_container").append(value.modelDetails);
                $.each(value.images, function(i, v) {
                $(".news_details_container").append('<img src="' + v+ '" />'); 
               });
             });
          });
   });

答案 1 :(得分:0)

您只返回单个父对象,因此您不需要在此时使用each。但是,您需要遍历返回的images属性。试试这个:

$("#driver").click(function() {
    $.getJSON("assets/data/one.json", function(data) {  
        var $container = $(".news_details_container");
        $container.append(data.item.name + ' ' + data.item.details + ' ' + data.item.composition + ' ' + data.item.modelDetails.join(' '));
        $.each(data.item.images, function(i, url) {
            $container.append('<img src="' + url + '" />'); 
        });
     });
});