首先,我要声明一个显而易见的事实:我对 html 很烂。 我的 javascript 编码水平相当,但我现在才发现 html 中 js 的严重限制。
案例:我的 Node.js 应用程序将错误日志输出到 json。 我制作了一个动态 html 表来排序和显示这些错误,所有这些都运行良好。
但是,当我处理完这些错误后,我希望在上述 html 页面上有一个按钮,用 [] 覆盖 json 文件,从而有效地使其再次空白。
现在,在 Node.js 中,使用 fs 很容易做到这一点,但在 html 中却没有这样的事情。 为了读取 json,我求助于 XMLhttprequest。
我很确定答案是我无法从客户端更改服务器上的数据。 这是有道理的,但是有解决方法吗?
<script>
Parser();
setInterval(function(){Parser()}, 300 * 1000)
function Parser() {
getJSON("Errors.json", function(err, data) {
let array = data;
let titles = ["Time", "Program", "", "Count", "Info", "Error"];
let text = [];
let joined = [];
let table = document.createElement("table");
let tr = table.insertRow(-1);
for (let i in titles) {
let th = document.createElement("th");
th.innerHTML = titles[i];
tr.appendChild(th);
}
for (let i in array) {
let count = 0;
array[i].count = 1;
for (let x in joined) {
let ar = array[i], jn = joined[x];
if (ar.file == jn.file && ar.line == jn.line && ar.info == jn.info && ar.message == jn.message){
count++;
jn.count++;
}
}
if (count == 0) joined.push(array[i])
}
for (let i in joined) {
let tx = joined[i]
text[0] = tx.time;
text[1] = tx.file;
text[2] = tx.line;
text[3] = "("+tx.count+"x)";
text[4] = tx.info;
text[5] = tx.message;
tr = table.insertRow(-1);
for (let j in text) {
let tabCell = tr.insertCell(-1);
tabCell.innerHTML = text[j];
}
}
let Table = document.getElementById("table");
Table.innerHTML = "";
Table.appendChild(table);
});
};
function getJSON(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "json";
xhr.onload = function() {
let status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
</script>
最佳答案
您发布的代码示例与您似乎已经自己回答的实际问题无关。您无权从浏览器访问文件系统。
但是,您可以让按钮向后端服务器发送 AJAX 请求来为您清除 JSON 文件。
关于javascript - 如何从 html 中更新 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48918837/