简体   繁体   中英

How can i update div's class and content without reloading the page on JSON update

So i have a JSON database which gets updated quite often based on which i update the content of my page. Currently i'm using this script for reload:

var previous = null;
var current = null;
setInterval(function() {
    $.getJSON("sampledatabase.json", function(json) {
        current = JSON.stringify(json);
        if (previous && current && previous != current) {
            console.log('refresh');
            location.reload();
        }
        previous = current;
    });
}, 1200);

The thing is it's supposed to be used for monitoring on a big screen in fullscreen so a blink when reloading is a bit distracting.

On refresh(which happens on database update) i'm changing the class of divs and also filling them with some more data from the database like this (just a part of code)

    var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        var i;
        var output = document.getElementsByClassName("env");
        var myObj = JSON.parse(this.responseText);
        for (i = 0; i < output.length; i++) {
            if (myObj.instances[i].status == "UP") {
                output[i].classList.add("passed")
            } else output[i].classList.add("notPassed")
            output[i].innerHTML = "<span class=\"originalsize\">" + myObj.instances[i].id + "</SPAN>" + "<br>" + myObj.instances[i].time
        }
    }

};
xmlhttp.open("GET", "sampledatabase.json", true);
xmlhttp.send();

Is there a way to update only the divs so i don't get the unpleasant blink when the page reloads?

You can use jQuery's $.ajax() method as W3 Schools explains.

Here is my JSFiddle

In my Fiddle I also used $.each() method to parse the JSON data and append it into divs.

function GetPosts() {
  $.ajax({
    dataType: "json",
    url: "https://jsonplaceholder.typicode.com/posts",
    success: function(data) {
      //console.log(data);
      $.each(data, function(index, item) {
        console.log(item);
        $('.container').append('<div class="posts"><div id="post_container"><h3 id="post_title">' + item.title + '</h3><hr><div id="post_body">' + item.body + '</div><hr><span id="post_userid">' + item.id + '</span></div></div>');
      });
    }
  });
}

You can also use setInterval() function to enable automatic updating.

In this case, you can do something like this:

let interval;
let time = 5000; // 5 seconds

function startRefresh() {
    interval = setInterval(GetPosts(), time);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM