3

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>
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

1

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.

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • 1
    It worked out perfectly. I have one last question. I have retrieved images but they are coming from a server and their resolution is different. So, I want to resize the images to one particular size like 200 x 200 – Abdur Rehman Farooqi Jun 06 '15 at 07:03
  • You could use `css` to resize the images and if you want a much deeper solution then you can read this http://stackoverflow.com/questions/787839/resize-image-proportionally-with-css – Mohd Abdul Mujib Jun 06 '15 at 07:13
  • And also, I'd like to mention that you can always create a new question, if you are having a new problem, this is a Q & A site, not a forum. – Mohd Abdul Mujib Jun 06 '15 at 07:15
0

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

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

$(selector).attr('src', imageUrl);
Jyoti Puri
  • 1,326
  • 10
  • 17