javascript - 从原始 json 获取不存在的数据并将其附加到表中
问题描述
我最近遇到了一些同样的问题,但无法从ing后的 json 响应中将数据附加到表中。fetch()
我的服务器使用来自数据库的日志呈现一个名为 tracker.ejs 的模板。我尝试获取,然后更新表格,但遗憾的是我无法确定表格中是否已经有一个类似的行。/api/track
响应类似于:
[
{"ip":"103.211.18.256","browser":"Chrome 89.0.4389.114","country":"India","os":"Linux","deviceType":"PC/Laptop"},
{"ip":"103.211.18.159","browser":"Chrome 89.0.4389.114","country":"India","os":"Linux","deviceType":"PC/Laptop"}
]
我的服务器设置了正确的 cors 策略,对此没有任何问题,但我的代码不起作用。
这是tracker.ejs:
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Track</title>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="/css/style.css">
<link rel="shortcut icon" type="image/jpg" href="/images/favicon.ico">
</head>
<body>
<p class="trackerfor">Tracking <a href="<%=url%>" class="trackinglink"><%=url%></a></p>
<center>
<table style="width: 100%;" class="table table-bordered table-dark table-striped table-hover logs">
<thead class="headers">
<tr>
<th class="ip">IP</th>
<th>Browser</th>
<th>Country</th>
<th>OS</th>
<th>Device Type</th>
</tr>
</thead>
<tbody id="log">
<%for (let object of info) {%>
<tr class="rows">
<td class="ip"><%=object.ip%></td>
<td><%=object.browser%></td>
<td><%=object.country%></td>
<td><%=object.os%></td>
<td><%=object.deviceType%></td>
</tr>
<%}%>
</tbody>
</table>
</center>
<script src="/js/main.js"></script>
</body>
</html>
使用 /js/main.js:
// from another stackoverflow question
function updateLogs(data, values) {
var log = document.getElementById("log");
log.innerHTML = "";
var x = "";
x += "<tr>";
values.forEach(value => {
console.log(data);
x += "<td>" + data[0][value] + "</td>";
x += "<td>" + data[1][value] + "</td>";
});
log.insertAdjacentHTML("beforeend", x);
};
window.onload = function() {
fetch("/api/track/" + url[url.length - 1]).then(res => res.json()).then(data => {
updateLogs(data, ["ip", "browser", "country", "os", "deviceType"]);
}).catch((e) => console.log(e));
}
如何使用此数据更新表中不存在的行?
解决方案
推荐阅读
- ruby - 如何从 cron 作业调用的脚本中停止服务?
- python - 如何让我的服务器通过 UDP 多播到 Internet 上的客户端?我需要一个特殊的多播 IP 地址吗?
- python - Python,函数,这里发生了什么?如果 lst1[index] != lst2[len(lst2) - 1 - index]
- javascript - 在 Node 中设置 AWS 开发工具包凭证
- ios - 我的 TableView 只列出了 itemArray 中的最后一项?
- amazon-web-services - aws Lex UI 不显示来自其他帐户的 lambda 函数
- django - Django 查询集获得前 3 名用户
- python - repo.checkout() :您对以下文件的本地更改将被 checkout 覆盖
- flutter - 谷歌使用 Flutter/Firebase 登录时如何获取 refreshToken
- javascript - 如何将事件侦听器添加到按钮元素