从json中获取所有数据并将其显示在索引页面上
Fetch all data from json and display it on the index page
我有以下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
等。
相关文章:
- 如何通过所选索引(AngularJS)在模态弹出窗口中显示数据
- 用于显示索引视图 Rails 中的页面的下拉链接
- 选择的索引未设置,除非显示警报
- 在网页上切换选项卡ui的最佳方式,z索引与显示
- 从json中获取所有数据并将其显示在索引页面上
- 点击JQuery/HTML5显示元素的索引/位置
- AngularJS ng-重复2D数组,并根据索引仅显示某些值
- 谷歌地图 Z 索引地图不显示
- 在模式窗口中显示页面上单击的值(链接)以及索引值
- 可选择序列化 jQuery UI::如何显示 html 标记中的内容而不是索引值
- 尝试使用PHP / Javascript构建一个可点击的索引,该索引显示单击的每个项目的数据
- 在索引上显示下拉列表更改了另一个下拉列表 .net 2.0
- 获取页脚以显示带有 z 索引的 AFTER 元素
- 查找突出显示文本的索引
- Highcharts,显示/隐藏共享工具提示时获取点索引
- Keystone,在索引页面上显示博客类别
- 绝对定位元素上的 z 索引显示在较高的 z 指数元素上方
- Rails Rendering从索引页以Bootstrap模式显示
- 如何在根页面上突出显示索引导航链接
- 以哈希值加载页面,然后直接显示结果,而不先显示索引