从json中获取所有数据并将其显示在索引页面上

Fetch all data from json and display it on the index page

本文关键字:显示 索引 json 获取 数据      更新时间:2023-09-26

我有以下json:

[
  {
    "countryId" : 0,
    "countryImg" : "../img/france.jpg",
    "countryName" : "France",
    "countryInfo" : {
      "headOfState" : "Francois Hollande",
      "capital" : "Paris",
      "population" : 66660000,
      "area" : 643801,
      "language" : "French"
    },
    "largestCities" : [
      {"Paris" : "../img/paris.jpg"},
      {"Marseille" : "../img/marseille.jpg"},
      {"Lyon" : "../img/lyon.jpg"}
    ]
  },
  {
    "countryId" : 1,
    "countryImg" : "../img/germany.jpg",
    "countryName" : "Germany",
    "countryInfo" : {
      "headOfState" : "Angela Merkel",
      "capital" : "Berlin",
      "population" : 81459000,
      "area" : 357168,
      "language" : "German"
    },
    "largestCities" : [
      {"Berlin" : "../img/berlin.jpg"},
      {"Munich" : "../img/munich.jpg"},
      {"Hamburg" : "../img/hamburg.jpg"}
    ]
  }
]

我需要把它放在我的index.html中,但是我不明白为什么我只得到第二个对象?我需要在索引中放入两个对象。也许我需要使用循环?我该如何正确地做到这一点?我有以下javascript代码:

$.ajax({
    method: "POST",
    url: "../data/data.json"
}).done(function (data) {
    /*console.log(data);*/
    localStorage.setItem('jsonData', JSON.stringify(data));
    var dataFromLocStor = localStorage.getItem('jsonData');
    var dataObject = JSON.parse(dataFromLocStor);
    console.log(dataObject);
    function Countries(){
        this.getCountries = function () {
            var ulListElem = document.getElementById("list-of-teams").children,
                imgCountry = document.createElement('img');
            for(country in dataObject){
                /*console.log(dataObject[team]['teamName']);*/
                imgCountry.setAttribute('src', dataObject[country]['countryImg']);
                imgCountry.setAttribute("width", "400");
                imgCountry.setAttribute("height", "300");
                console.log(country);
                ulListElem[0].innerHTML = dataObject[country]['countryId'];
                ulListElem[1].innerHTML = dataObject[country]['countryName'];
                ulListElem[2].appendChild(imgCountry);
                ulListElem[3].innerHTML = dataObject[country]['countryInfo']['headOfState'];
                ulListElem[4].innerHTML = dataObject[country]['countryInfo']['capital'];
                ulListElem[5].innerHTML = dataObject[country]['countryInfo']['population'];
                ulListElem[6].innerHTML = dataObject[country]['countryInfo']['area'];
                ulListElem[7].innerHTML = dataObject[country]['countryInfo']['language'];
            }
        }
    }
    var countriesDate = new Countries();
    countriesDate.getCountries();
});

您在循环中设置了两次相同的UI元素(img和ul)。当循环第一次运行时,从第一个数组元素设置值。当循环第二次运行时,SAME元素将被新值覆盖。

为了正确显示JSON数组中的所有元素,在index.html页面中需要两组UI元素,例如两个img、两个ul等。