【问题标题】:How can i update div's class and content without reloading the page on JSON update如何在不重新加载 JSON 更新页面的情况下更新 div 的类和内容
【发布时间】:2018-05-25 20:54:42
【问题描述】:

所以我有一个 JSON 数据库,它经常根据我更新页面的内容进行更新。目前我正在使用这个脚本重新加载:

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);

问题是它应该用于在大屏幕上全屏监控,所以重新加载时眨眼有点分散注意力。

刷新时(在数据库更新时发生)我正在更改 div 的类,并用数据库中的更多数据填充它们(只是代码的一部分)

    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();

有没有办法只更新 div,这样我就不会在页面重新加载时出现令人不快的闪烁?

【问题讨论】:

  • location.reload() 替换为来自XMLHttpRequest 的成功回调,然后丢弃XMLHttpRequest。 (为什么要同时使用XMLHttpRequest$.getJSON?)

标签: javascript jquery html css ajax


【解决方案1】:

您可以按照W3 Schools 的说明使用jQuery 的$.ajax() 方法。

这是我的JSFiddle

在我的 Fiddle 中,我还使用了 $.each() 方法来解析 JSON 数据并将其附加到 div 中。

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>');
      });
    }
  });
}

您也可以使用setInterval()函数来启用自动更新。

在这种情况下,您可以这样做:

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

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

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 2015-02-24
    • 2017-12-13
    • 1970-01-01
    • 2010-12-22
    • 2021-07-17
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多