[英]How can I loop over this JSON file and get the data?
I want to append the "tourism" data to one div and the "bikes" data to another div我想将“旅游”数据附加到一个 div,将“自行车”数据附加到另一个 div
I also want to get both data structures on a single click event我还想在一个单击事件上获得两个数据结构
[
{
"city1" : {
//this is the first data that should be appended to one div
"tourism" : [{
"objectId":"1a1",
"objectTitle":"title_text",
"objectUrl_image":"http://",
"object_textContent":"text_content"
},
{
"objectId":"1a2",
"objectTitle":"title_text",
"objectUrl_image":"http://",
"object_textContent":"text_content"
}],
//this is another data that should be appended to another div
"bikes" : [{
"objectId":"1b1",
"objectTitle":"title_text",
"objectUrl_image":"http://",
"object_textContent":"text_content"
},
{
"objectId":"1b2",
"objectTitle":"title_text",
"objectUrl_image":"http://",
"object_textContent":"text_content"
}]
}
}
]
Try this is in success call back of AJAX call.试试这是 AJAX 调用的成功回调。
success: function(result) {
var tourism=JSON.parse(result.city.tourism);
var bikes =JSON.parse(result.city. bikes);
var tourismLen=tourism.length;
for(var i=0;i<=tourismLen;i++) {
console.log(tourismLen[i].objectTitle);
}
}
A simple forEach
for the tourism and bikes properties would do:一个简单的forEach
用于旅游和自行车属性会做:
const data = [{ "city1": { //this is the first data that should be appended to one div "tourism": [{ "objectId": "1a1", "objectTitle": "title_text", "objectUrl_image": "http://", "object_textContent": "text_content" }, { "objectId": "1a2", "objectTitle": "title_text", "objectUrl_image": "http://", "object_textContent": "text_content" }], //this is another data that should be appended to another div "bikes": [{ "objectId": "1b1", "objectTitle": "title_text", "objectUrl_image": "http://", "object_textContent": "text_content" }, { "objectId": "1b2", "objectTitle": "title_text", "objectUrl_image": "http://", "object_textContent": "text_content" }] } }]; const divTourism = document.getElementById('tourism'); const divBikes = document.getElementById('bikes'); const generateImageWrapper = function (item, container) { const imageWrapper = container.appendChild(document.createElement('div')); const image = imageWrapper.appendChild(document.createElement('img')); const text = imageWrapper.appendChild(document.createElement('p')); image.title = item.objectTitle; image.src = item.objectUrl_image; text.appendChild(document.createTextNode(item.object_textContent)); imageWrapper.classList.add('image-wrapper'); }; data.forEach((item) => { item.city1.tourism.forEach((tourism) => { generateImageWrapper(tourism, divTourism); }); item.city1.bikes.forEach((bike) => { generateImageWrapper(bike, divBikes); }); });
.image-wrapper { display: inline-block; padding: 10px; text-align: center; } .image-wrapper img { background: #eee; height: 100px; width: 100px; }
<div id="tourism"> <h1> Tourism </h1> </div> <div id="bikes"> <h1> Bikes </h1> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.