Dean Coulstock
Dean Coulstock

Reputation: 3

Appending JSON data to an HTML element

I'm trying to:

  1. Fetch JSON data using $.get

  2. append that data to an HTML element $('photos') so that images are displayed using the external JSON file instead of in-line HTML.

I'm not getting any console errors and the images aren't displaying. Any help would be EXTREMELY appreciated. Thanks a lot. I have an alert to check if the JSON is loaded, and it loads fine- just doesn't change any data.

Here is my current setup:

(JSON): photoData.json

{  "photos": {
"1": {
  "href": "./photos/photo1.JPG",
  "src": "photos/photo1.JPG",
},
"2": {
  "href": "./photos/photo2.JPG",
  "src": "photos/photo2.JPG",
},
"3": {
  "href": "./photos/photo3.JPG",
  "src": "photos/photo3.JPG",
},
"4": {
  "href": "./photos/photo4.JPG",
  "src": "photos/photo4.JPG",
},
"5": {
  "href": "./photos/photo5.JPG",
  "src": "photos/photo5.JPG",
}}}

jQuery:

$.get("./data/photoData.json", function(photos){
alert("Data Loaded: " + photos);
let htmlStr = "";
for (let i = 0; i < photos.length; i++){
    htmlStr += `<figure><a href="${photos[i].href}"><img src = "${photos[i].src}"></img></a></figure>`
}
$('Photos').html(htmlStr);});

Upvotes: 0

Views: 70

Answers (1)

Andy
Andy

Reputation: 63524

photos is a object of objects not an array. So use for...in instead:

$.get("./data/photoData.json", function(data) {
  const photos = data.photos;
  let htmlStr = '';
  for (let photo in photos) {
    htmlStr += `<figure><a href="${photos[photo].href}"><img src="${photos[photo].src}"></img></a></figure>`
  }
});

And something that's been raised in the comments: $('Photos') is not a valid jQuery selector. I suspect that you have an element with an id called Photos - you just need to add the hash to the selector: $('#Photos').

DEMO

Upvotes: 1

Related Questions