natlotzy
natlotzy

Reputation: 97

Get image from JSON file using JavaScript and display in HTML img tag

I'm really unsure what I'm doing wrong here. My code makes sense to me, but then again I guess I'm just a beginner. Seems so simple yet I can't figure it out. Any help would be great, please and thank you.

Please read code comments for specifications of what I'm trying to do.

JSON code:

{"images":[
{
    "bannerImg1":"./images/effy.jpg"
}]}

JavaScript:

$.getJSON('data.json', function(data) { // Get data from JSON file
for (var i in data.images) {
    var output+=data.images[i].bannerImg1; // Place image in variable output
}
document.getElementById("banner-img").innerHTML=output;}); // Display image in the img tag placeholder

HTML:

<div class="banner-section">
    <!-- Image should load within the following img tag -->
    <img class="banner-img" alt="effy">
</div>

Upvotes: 2

Views: 68992

Answers (3)

Sigismundus
Sigismundus

Reputation: 625

Create an Image object (with needed attributes) and add it to the exiting div

var data = {
  "images": [{
    "bannerImg1": "https://i.sstatic.net/HXS1E.png?s=32&g=1"
  },
  {"bannerImg1" : "https://i.sstatic.net/8ywqe.png?s=32&g=1"
  }]
};
data.images.forEach( function(obj) {
  var img = new Image();
  img.src = obj.bannerImg1;
  img.setAttribute("class", "banner-img");
  img.setAttribute("alt", "effy");
  document.getElementById("img-container").appendChild(img);
});
<div class="banner-section" id="img-container">
    </div>

Upvotes: 6

Balkrushn
Balkrushn

Reputation: 91

  1. Put a div in a body with attribute id picture e.g.<div id="picture"></div>
  2. Append img tag to the div

    //code
    success : function(data) {
                  var returnData = jQuery.parseJSON(data);           
                  $("#picture").append("<img src=\" + returnData.img_url + "\" />");
               });
    //code if any
    

Upvotes: 2

Ringo
Ringo

Reputation: 3965

Try this:

    $.getJSON('data.json', function(data) { // Get data from JSON file
     try{
      var json = $.parseJSON(data);
      for (var i =0; i< json.images.length; i++) {
        var output+=json.images[i].bannerImg1; // Place image in variable output
     }
      document.getElementById("banner-img").innerHTML=output;
     }catch{}
    }); 

Upvotes: 0

Related Questions