我一直在尝试创建一个jQuery请求循环,根据结果每隔X秒重新加载一次内容。
我有这个JS:
$(document).ready(function(){
function init(){
$.ajax({
url: 'screen.php',
data: {
'screen' : <?php echo $screen_id; ?>
},
async: true,
success: function(r){
JSON.parse(r, function(k, v){
if(k == 'screen_content'){
var content = v;/* $('.content').html(v); */
}
if(k == 'visible_seconds'){
setTimeout($('.content').html(content),v);
/* (function(){}).delay(timer); */
/* $().delay(function(msg) { console.log(msg); }, v, 'Hello'); */
}
});
/* init(); */
}
});
}
init();
});
结果是一个JSON字符串,其X号为&#34; screen_content&#34;和&#34; visible_seconds&#34;配对。我需要显示&#34; screen_content&#34; in&#34; visible_seconds&#34;秒,然后用JSON中的下一个内容更改内容 - 当所有内容都显示时,它都会重新开始(所以我们可以获取新内容)
我脑子里似乎很简单,但我不能为它创建jQuery:/
答案 0 :(得分:1)
你需要这样的东西:
$(document).ready(function() {
function getContent(){
$.ajax({
url: 'screen.php',
data: {
'screen' : <?php echo $screen_id; ?>
},
async: true,
success: function(contentArray){
return showAllContent(contentArray);
}
});
}
var i = 0;
function showContent(contentArray, count){
var currContentData = contentArray[count];
$('.content').html(currContentData.content);
setTimeout(function() {
return showAllContent(contentArray);
}, currContentData.duration);
}
function showAllContent(contentArray){
if(i === contentArray.length){
i = 0;
return getContent(showAllContent);
}
return showContent(contentArray, i++);
}
getContent();
});
我假设您的ajax调用返回以下结构中的数据:
[{
content: 'content 1',
duration: 1000
}, {
content: 'content 2',
duration: 2000
}]
使用虚拟函数代替ajax调用here。