Reputation: 137
My Requirement is : I have a json object which contains some URL(URL is the URL of a image) and their names.I want to iterate through the JSON object and want to get the URL's (nothing but a image) and want to append the image into a div.So that i can see the images from the JSON object. suppose this is my code
var JSON = [{"name:"A","url":".../a.jpg"},{"name:"B","url":".../b.jpg"},{"name:"C","url":".../c.jpg"} I want to iterate through this object, get the name and the URL and want to append the name and URl to a div(with some div ID) in my HTML. Detailed code would be helpful. Thanks for the help in advance.
Upvotes: 2
Views: 2782
Reputation: 6950
A complete example :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var jsonData = [{"name":"A","url":".../a.jpg"},{"name":"B","url":".../b.jpg"},{"name":"C","url":".../c.jpg"}];
var imgContainer = $("#imgContainer");
$.each(jsonData,function(key,value){
console.log(imgContainer);
imgContainer.append('<img title="'+value.name+'" src="'+value.url+'" />');
})
});
</script>
</head>
<body>
<div id="imgContainer"> </div>
</body>
</html>
Upvotes: 4
Reputation: 382
Inspired by Rajesh CP
function test() {
var JSON = [{ name: "A", url: "http://www.w3schools.com/images/pulpit.jpg" }, { name: "B", url: "http://www.w3schools.com/images/pulpit.jpg" }, { name: "C", url: "http://www.w3schools.com/images/pulpit.jpg" }];
var element = $("#divID");
$(myArray).each(function (key) {
html = '';
html += '<div class="example_result notranslate" style="text-align:center">\n'
html += '\t<h2>' + JSON[key].name + '</h2>\n';
html += '\t<img src="' + JSON[jey].url + '">\n';
html += '</div>\n';
html += '<br>\n';
element.append(html);
});
}
Upvotes: 0
Reputation: 3645
var data = [{name:"A",url:".../a.jpg"},{name:"B",url:".../b.jpg"},{name:"C",url:".../c.jpg"}];
var div = document.getElementById("#id");
data.forEach(function(item, index){
div.innerHTML = div.innerHTML + ("Name:" + item.name + " URL:" + item.url + "<br>");
});
Upvotes: 0