我有这个显示JSON数据的代码。如何重新编写代码以每30秒显示一次随机JSON数据?
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
var data= response.data;
var output = '';
for(var i = 0;i < data.length;i++){
output += ''+data[0].data1+''+data[0].data2+'<br/>';
}
document.getElementById('placeholder').innerHTML = output;
}
};
xhttp.open("GET", "url.json", true);
xhttp.send();
以下是JSON
的示例{
"data": [
{
"data":"John",
"data2": "Doe"
},
{
"data":"Nick",
"data2": "Doe"
},
]
}
如何最好与setInterval一起使用,以便显示一分钟的“John Doe”和其他“Nick Doe”?
答案 0 :(得分:1)
创建setInterval
每隔30秒调用一次逻辑。最初设置index=0
并在等于json的长度时重置。
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
var data= response.data;
var output = '';
var index = 0; // set your index
setInterval(function(){
if (index == data.length){
index= 0; // reset when equals json's length
}
output = ''+data[index].data1+''+data[index].data2+'<br/>';
document.getElementById('placeholder').innerHTML = output;
index++; // move to next element
},30000);
}
};
xhttp.open("GET", "url.json", true);
xhttp.send();