有没有办法实时从 json 读取数据到 html?

Is there a way to read data from json to html realtime?

对于学校项目,我将电报消息实时写入 JSON 文件。现在我想在 JSON 收到新消息时更新我的​​ HTML。我的 HTML 与 JQuery/Knockout.js 一起工作。执行此操作的最佳方法是什么?

$(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