Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Multiple images from JSON using jQuery

This is the code that takes data in the form of json and it 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>
like image 281
Abdur Rehman Farooqi Avatar asked Dec 18 '25 12:12

Abdur Rehman Farooqi


1 Answers

You could use, .each() function from jQuery as shown below.

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

And IMHO since you are also appending the returned images you ought to name the function likewise, just to avoid the confusion later.

so your function becomes

function appendReturnedImages(data) {

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

Also the DOM element that you are appending to is an img, since an img cant contain other img, you have to make it a div as below.

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

Edit:- Since I didnt have the returned JSON dataset, I didnt have the chance to test my solution, but it should work, just try fiddling a little bit if it doesnt.

like image 57
Mohd Abdul Mujib Avatar answered Dec 21 '25 02:12

Mohd Abdul Mujib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!