Displaying multiple images from JSON using jQuery

This is the code that takes data in json form and looks like this:

function json2array() {

  var data = {"images": [

  "https:\/\/outpan-images.s3.amazonaws.com\/rg6j1l9iqd-0078915030900.jpg",

  "https:\/\/outpan-images.s3.amazonaws.com\/835ggkjjq0-0078915030900.png",

  "https:\/\/outpan-images.s3.amazonaws.com\/8fn652ptobh3ecw886.jpg",

  "https:\/\/outpan-images.s3.amazonaws.com\/26naopw9flteq3qrcs.jpg",

  "https:\/\/outpan-images.s3.amazonaws.com\/uhqq6sdj47-0078915030900.jpg"

]};

  var keys = Object.keys(data);

  keys.forEach(function(key) {

    result.push(data[key]);



  });

  $("#myElement #images").append($('<img>', {
    src: result[key]
  }));

  //  return result;

}
      

<div class="container-fluid" id="myElement">
    <img id="images"> </img>
</div>
      

Run codeHide result


+3


source to share


2 answers


Please check this fiddle: https://jsfiddle.net/cjkfgjv9/

To dynamically change the src of an image element use this jQuery syntax:



$(selector).attr('src', imageUrl);

      

0


source


You can use the function .each()

from jQuery

as below.

$.each(data.images, function(index, element) {
    alert(element); 
});

      

And IMHO, since you are also adding the returned images, which you should also call a function, just to avoid confusion later.

so your function will become



function appendReturnedImages(data) {

  $.each(data.images, function(index, element) {
    $("#myElement #images").append($('<img>', {
      src: element
    }));
  });
}

      

Also, the DOM element you are adding is img

, since the element img

contains others img

, you should make it div

like below.

<div class="container-fluid" id="myElement">
 <div id="images"> </div>
</div>

      

Edit: - Since I didn't have the JSON dataset returned, I didn't have a chance to test my solution, but it should work, just try playing around a bit if it doesn't.

+1


source







All Articles