Reputation: 621
The basic set up is a simple JSON file which I am pulling into a page via ajax. Now I've got it working fine with this code
$(document).ready(function () {
var tour = $('.js-featureTour');
$.ajax({
type: "GET",
url: "tour.json",
dataTyple: "json",
success: function (result) {
var imgSrc = result.image;
$('.js-featureTourTitle').text(result.tourTitle);
$('.js-featureTourDesc').html(result.tourDesc);
$('.js-featureTourImg').attr('src', imgSrc);
}
})
});
This worked well with my test JSON file but what I actually have to work with is something like this
{
"tour1": {
"tourTitle": "Test Title 1",
"tourDesc": "description 1",
"image": "/main1.jpg"
},
"tour2": {
"tourTitle": "Test Title 2",
"tourDesc": "description 2",
"image": "/main2.jpg"
},
"tour3": {
"tourTitle": "Test Title 3",
"tourDesc": "description 3",
"image": "/main3.jpg"
}
}
What I really want is for the success stage to read what is in "tour1" insert it into the page, then wait for a bit then read what is in "tour2" and over write the "tour1" information and then do the same for "tour3". Can anyone help me out here? I've been stuck on this for longer than I care to admit. Any help is greatly appreciated.
Upvotes: 2
Views: 433
Reputation: 621
Just for the record I got it working with this
success: function (result) {
var time = 0;
$.each(result, function(i, result) {
setTimeout(function(){
var imgSrc = result.image;
$('.js-featureTourTitle').text(result.tourTitle);
$('.js-featureTourDesc').html(result.tourDesc);
$('.js-featureTourImg').attr('src', imgSrc);
},time)
time += 5000;
})
}
Thanks for the help!
Upvotes: 0
Reputation: 4832
You need to loop through the Json Object and use SetTimeout
to delay the manipulation of data in DOM. Try try below code.
success: function (result) {
$.each(results, function(i,result) {
setInterval(function(){
var imgSrc = result.image;
$('.js-featureTourTitle').text(result.tourTitle);
$('.js-featureTourDesc').html(result.tourDesc);
$('.js-featureTourImg').attr('src', imgSrc);
},5000)
})
}
Upvotes: 1
Reputation: 76573
You can do this with setInterval
:
function handleTours(json) { //call this from the callback
var elements = []; //build a set of elements which will help
for (key in json) {
elements.push(key: key, structure: json[key]);
}
if (elements.length > 0) { //if there are no elements, do nothing
var index = 0;
var intervalID = setInterval(function() { //we store intervalID to stop the repetition when we are at the end of the set
if (index >= elements.length) {
clearInterval(intervalID); //we are at the end of the set
} else {
//do something with elements[index].key and elements[index].structure
index++;
}
}, 5000);
}
}
Upvotes: 0