从JSON中提取多个数据集
问题描述:
基本设置是一个简单的JSON文件,我通过ajax将其拉入页面。现在我知道了工作的罚款,此代码从JSON中提取多个数据集
$(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);
}
})
});
这与我的测试JSON文件效果很好,但我确实有一起工作是这样的
{
"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"
}
}
我真正想要的是为了成功读取“tour1”中的内容,将其插入页面,然后等待一段时间,然后阅读“tour2”中的内容,然后写入“tour1”信息,然后执行“tour3”的相同操作。有人可以帮我从这里出去吗?我一直坚持这一点的时间超过了我的承认。任何帮助是极大的赞赏。
答
您需要遍历Json对象并使用SetTimeout
来延迟DOM中数据的操作。尝试下面的代码。
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)
})
}
答
你可以用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);
}
}
答
只是为了记录
我得到了它这个
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;
})
}
感谢您的帮助工作!
嘿!感谢您的回应。这种有点奏效,但它不显示tour1和tour2,而是等待5秒,然后显示tour3 – Damien
尝试使用上面的代码。我已经修改它通过使用$ .each而不是foreach –
再次感谢,我仍然得到相同的结果,但:(这是我第一次跳入ajax/JSON,所以道歉为做noob – Damien