使用JavaScript和jQuery加载本地JSON文件

时间:2018-11-15 15:08:40

标签: javascript jquery html json

我正在尝试将JSON文件的内容加载到JS文件中并将其写入我的主HTML文件,但是不确定如何处理。

到目前为止,我所做的如下:

index.html:

<p>
    Name: <span id="dogName1"></span><br>
    Breed: <span id="dogBreed1"></span><br>
    Age: <span id="dogAge1"></span><br>
    Image: <span id="dogImage1"></span><br>
</p>

package.json:

{
  "name":"pets",
  "Dogs":[
    {
      "Name":"Oliveander",
      "Breed":"German Shepherd",
      "Age":3,
      "Image":"images/GermanShepherd.jpg"
    },
    {
      "Name":"Ripley",
      "Breed":"Golden Retriever",
      "Age":5,
      "Image":"images/GoldenRetriever.jpg"
    },
    {
      "Name":"Remi",
      "Breed":"Siberian Husky",
      "Age":2,
      "Image":"images/SiberianHusky.jpg"
    }
  ]

main.js:

$.getJSON( "data/package.json", function( json ) {
    console.log( "JSON Data received, name is " + json.name);
});

到目前为止,我所能理解的是,我在JS文件中拥有的代码就是我加载JSON文件的方法,但是我不确定如何继续

2 个答案:

答案 0 :(得分:0)

您可以像下面这样简单地迭代json数据

firebase.database().ref('test').on('value', (snapshot) => {
    if(snapshot.exists()) {
        console.log('I have data')
    }
})
var jsonData = {
  "name":"pets",
  "Dogs":[
    {
      "Name":"Oliveander",
      "Breed":"German Shepherd",
      "Age":3,
      "Image":"images/GermanShepherd.jpg"
    },
    {
      "Name":"Ripley",
      "Breed":"Golden Retriever",
      "Age":5,
      "Image":"images/GoldenRetriever.jpg"
    },
    {
      "Name":"Remi",
      "Breed":"Siberian Husky",
      "Age":2,
      "Image":"images/SiberianHusky.jpg"
    }
  ]
  }
  for(var i=0;i<jsonData.Dogs.length;i++){
    console.log("Name : "+ jsonData.Dogs[i].Name)
    console.log("Age : "+ jsonData.Dogs[i].Age)
    console.log("Bread : "+ jsonData.Dogs[i].Bread)
    console.log("------------------------------------")
  }

答案 1 :(得分:0)

我认为您正在寻找的是jQuery append()方法。您可以这样使用它:

$(document).ready(function () {
    $.getJSON( "data/package.json", function( json ) {
        console.log( "JSON Data received, name is " + json.name);
        for(let i in json.Dogs){
            var dog = json.Dogs[i];
            $("#dogTable").append(getDogMarkup(dog));
        }
    });
});

function getDogMarkup(dog){
    return 'Name: <span class="dogName">' + dog.Name + '</span><br>' +
    'Breed: <span class="dogBreed">' + dog.Breed + '</span><br>'+ 
    'Age: <span id="dogAge1">' + dog.Age + '</span><br>'+ 
    'Image: <span id="dogImage1">//image html here</span><br><br>';
}

您需要做的是在HTML中创建一个锚点,您可以在其中填充所需的数据,例如:<div id="dogTable"></div>