通过嵌套的JSON对象创建html元素

时间:2017-06-08 08:20:29

标签: javascript jquery json

所以我之前成功地通过JSON对象创建了HTML元素,但是现在我已经将我的JSON对象更改为嵌套的JSON,我无法相应地重现HTML元素。我对编程很陌生,所以任何人都可以帮我找出我出错的地方吗?

JSON文件:

{  
  "ThreeG": [
    {
        "title":"Testing 1",
        "filePath":"https://example.com",
        "imagePath":"images/test.jpg"
    },
    {
        "title":"Testing 2",
        "filePath":"https://example.com",
        "imagePath":"images/test2.jpg"
    }
   ]
}

脚本:

<script>
    $.ajax({
      url : "TestFiles.json",
      type : "post", 
      contentType:"application/json",
      success : function(list){           
          var divCol  = "<div class='col-md-offset-1 col-sm-5 col-md-5'>";
          var divWell = "<div class='well' style='position:relative'>";
          var divClose= "</div>";

          list.forEach(function(obj, index) {

            var title     = "<h4>"      + obj.ThreeG.title    + "</h4>";
            var linkStart = "<a href='" + obj.ThreeG.filePath + "' target='_blank'>" ;
            var image     = "<img data-toggle='tooltip' data-placement='left' title='Click to open data' src='" + obj.ThreeG.imagePath + "' height='100%' width='100%'/>"
            var linkEnd   =  "</a>";

            var div = divCol    +
            divWell     +
            title       +
            linkStart       +
            image       +
            linkEnd +
            divClose +
            divClose;

            console.log(obj);
           $("#test").append(div); 

           })
        }
    });
  </script>

2 个答案:

答案 0 :(得分:1)

成功回调中的list参数是一个具有属性/键ThreeG的对象。因此,您应该执行list.forEach而不是list.ThreeG.forEach,然后forEach回调中的每个obj将成为可用于创建HTML元素的json对象。

list.ThreeG.forEach(function(obj, index) {
         console.log(obj); // { "title":"Testing 1", "filePath":"https://example.com", "imagePath":"images/test.jpg" } for the first object
}

答案 1 :(得分:0)

var obj = {  
  "ThreeG": [
    {
        "title":"Testing 1",
        "filePath":"https://example.com",
        "imagePath":"images/test.jpg"
    },
    {
        "title":"Testing 2",
        "filePath":"https://example.com",
        "imagePath":"images/test2.jpg"
    }
   ]
};

for(var i=0;i<obj.ThreeG.length;i++) {
var data = obj.ThreeG[i];//Take a reference here
console.log(data.title, data.filePath, data.imagePath);
}

您不能说obj.ThreeG.title,因为obj.ThreeGarray。您需要使用obj.ThreeG[0].titleobj.ThreeG[1].title等。

如上所示进行一些循环。