首页 > 解决方案 > 从原始 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));
}

如何使用此数据更新表中不存在的行?

标签: javascript

解决方案


推荐阅读