Exercise - jQuery AJAX
Photo Handling
by Ryan Morris
HTML
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<div class="container">
<h2>Photos</h2>
<div id="album">
<p>We want our photos to show up here.</p>
</div>
</div>
<script id="photo-template" type="text/x-handlebars-template">
<div class="entry">
<h6>{{title}}</h6>
<img src="{{thumbnailUrl}}" alt="{{id}}" />
</div>
</script>
CSS
#album img{
width:20px;
height:20px;
}
JavaScript
var photoTemplate = Handlebars.compile(
$("#photo-template").html()
);
$.ajax({
url: 'https://jsonplaceholder.typicode.com/photos',
data: {
albumId: 10
},
success: function (response) {
var $album = $("#album");
// for each array item
response.forEach(function (item) {
// render an album item
var newImg;
newImg = "<img ";
newImg += "src='" + item.thumbnailUrl + "' ";
newImg += " />";
// or...
// with jquery
/*newImg = $("<img "
+ "src='" + item.thumbnailUrl + "' "
+ " />"
);/**/
// or...
// with a template
//var newImg = photoTemplate(item);
$album.append(newImg);
});
},
dataType: 'json'
});