Reputation: 117
I am trying to insert images from a json file using Ajax. These images will then be used by the owl carousel, however currently it is only displaying the last image in json file.
Here is my code:
html
<div class="content newFilms">
<h2 class="welcomeText">New Releases</h2>
<div class="owl-carousel owl-theme"></div>
</div>
js
$(document).ready(function() {
$.getJSON("data/owl.json",function(img){
$.each(img, function(index,img){
var $newImg = $(img.item);
$(".owl-carousel").append($newImg);
});
$(".owl-carousel").owlCarousel({
dots:true
});
});
});
json
[
{
"item":"<img src='images/slide1.jpg'/>",
"item":"<img src='images/slide2.jpg'/>",
"item":"<img src='images/slide3.jpg'/>"
}
]
Upvotes: 0
Views: 1943
Reputation: 338228
You can't have multiple identical keys in the same object.
I suggest a different data structure. A top-level object that has an images
property, which is an array of objects, each carrying information about a single image.
{
"images": [
{"url": "images/slide1.jpg"},
{"url": "images/slide2.jpg"},
{"url": "images/slide3.jpg"}
]
}
Then the code follows naturally:
$(document).ready(function() {
$.getJSON("data/owl.json").done(function (data) {
$.each(data.images, function(index, img) {
$('<img>', { src: img.url }).appendTo(".owl-carousel");
});
$(".owl-carousel").owlCarousel({
dots:true
});
});
});
Note that it's not a good idea to have the finished HTML inside your JSON, as this limits what you can do with it on the client side and leads to useless duplication in the JSON data.
jQuery makes it quite easy to build HTML elements from data, make use of that feature and only include the actual data in the JSON. The client-side code can take care of the details how to render it.
Upvotes: 1