有没有办法从json读取数据到html实时?
对于一个学校项目,我将电报消息实时写入JSON文件。现在我想在JSON中添加新消息时更新我的HTML。我的HTML与JQuery/Knockout.js一起工作。做这个的最好方式是什么 ?有没有办法从json读取数据到html实时?
$(document).ready(function(){
var viewModel = function() {
console.log('test');
$.getJSON('/apps/telegram/getmessages', function(data) {
//console.log(data["messages"]);
var jsondata = data["messages"];
console.log(jsondata);
for(index = 0; index<jsondata.length; ++ index){
console.log(jsondata[index]);
var message = jsondata[index]["message"];
var firstname = jsondata[index]["first_name"];
console.log(message);
$('#messages').append('<p>' + message + '</p>');
}
})
.error(function(error){
console.log(error);
});
}
ko.applyBindings(viewModel);
})
要近实时地进行更新,使用已有代码的最简单方法是设置代码向服务器请求更新数据的时间间隔。这将在区间反复运行相同的代码指定:
setInterval(function() {
console.log('test');
$.getJSON('/apps/telegram/getmessages', function(data) {
//console.log(data["messages"]);
var jsondata = data["messages"];
console.log(jsondata);
for(index = 0; index<jsondata.length; ++ index){
console.log(jsondata[index]);
var message = jsondata[index]["message"];
var firstname = jsondata[index]["first_name"];
console.log(message);
$('#messages').append('<p>' + message + '</p>');
}
})
.error(function(error){
console.log(error);
});
},
1000); //1000 milliseconds (1 second). Change the value to whatever you need.
详情请参阅https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval。
这似乎并不是真的有效,我仍然需要刷新才能看到任何更改。 –
你应该不需要。你能在控制台看到函数是否每1秒运行一次?它是否在返回新的消息数据?如果你的getJSON函数需要1秒以上的时间才能返回结果,那么唯一的缺陷就是它可能会有点不同步。 – ADyson
它有效,但有一个问题:每秒钟都会一遍又一遍地打印新消息。有没有办法只能打印一次? –
嗨。请阅读[问]和[主题](https://stackoverflow.com/help/on-topic),特别是有关家庭作业的部分,并使用[mcve] –
重新编写代码,该代码看起来大致可以。什么不工作? – ADyson
告诉我们什么是不工作 –