我编写了一个简单的脚本,每分钟都会在div中加载一个内容。 div内容来自ajax调用。我的代码如下:
setInterval(function() {
$.get("scrollrtl.php?id=1", function(data){
$('.messaggi').html(data);
});
}, 1000 * 60 * 1);
我有以下json数组:
[
Object { id="1", template="scrollrtl"},
Object { id="3", template="scrollrtl"},
Object { id="6", template="scrollrtl"}
]
如何更新我的代码,以便每次在url中运行ajax调用而不是id = 1时,我可以将其中一个id放入数组中? 所以我第一次有
$.get("scrollrtl.php?id=1", function(data){
$('.messaggi').html(data);
});
第二次
$.get("scrollrtl.php?id=3", function(data){
$('.messaggi').html(data);
});
第三次
$.get("scrollrtl.php?id=6", function(data){
$('.messaggi').html(data);
});
更准确地说,url(数组中的模板可能会改变)但逻辑是相同的。每个时间之间的转换由setInterval设置为每分钟。
答案 0 :(得分:2)
对于随机订单
var obj = [
{ id:"1", template:"scrollrtl"},
{ id:"3", template:"scrollrtl"},
{ id:"6", template:"scrollrtl"}
];
function getId(){
return obj[Math.floor(Math.random() * 3)].id;
}
setInterval(function() {
$.get("scrollrtl.php?id=" + getId(), function(data){
$('.messaggi').html(data);
});
}, 1000 * 60 * 1);
按顺序
var obj = [
{ id:"1", template:"scrollrtl"},
{ id:"3", template:"scrollrtl"},
{ id:"6", template:"scrollrtl"}
]
var index = 0;
setInterval(function() {
$.get("scrollrtl.php?id=" + obj[index].id, function(data){
$('.messaggi').html(data);
});
index++;
index == obj.length ? index = 0 : false;
}, 1000 * 60 * 1);
答案 1 :(得分:2)
// set an index that will be used to iterate through the array
var index = 0;
// make sure you use colons not equals signs in your object.
// your syntax was wrong
var arr = [
{ id:"1", template:"scrollrtl"},
{ id:"3", template:"scrollrtl"},
{ id:"6", template:"scrollrtl"}
];
// have a function that performs the action.
function doThing() {
$.get("scrollrtl.php?id=" + arr[index].id, function(data){
$('.messaggi').html(data);
});
// increase the index
index++;
// if the index is less than the length of the array
// use a setTimeout (not setInterval) to call the function again
// otherwise don't call the function again (obvs)
if (index < arr.length) {
setTimeout(doThing, 1000 * 60 * 1);
}
}
// call doThing() to set the process going
doThing();
DEMO - 该示例每隔一秒而不是一分钟将对象记录在当前索引处。作为示例。