服务器,如何为一个简单的json数组映射数据



我是一个java脚本新手,这就是为什么我很难映射一个简单的json数组,如果它是来自服务器的响应的话。我已经用静态json测试了它,它可以像预期的那样工作:

new gridjs.Grid({
columns: [{
id: 'dateTime',
name: 'Timestamp'
}, {
id: 'host',
name: 'Host'
}, {
id: 'ipv4',
name: 'IPv4'
}, {
id: 'ipv6',
name: 'IPv6'
}],
data: [
{"dateTime": "2021-12-02 03:11:30.501","host": "master.myhost.com","ipv4": "93.215.66.14", "ipv6": "2003:cc:2fff:9e4:2e91:abff:febf:d839"}, 
{"dateTime": "2021-12-02 03:44:29.494", "host": "test.myhost.com", "ipv4": "93.203.250.190", "ipv6": "n/a"}, 
]
}).render(document.getElementById("wrapper"));

但是,如果服务器提供相同的json数组,我不知道如何定义我的数据映射。这就是我尝试过的:

new gridjs.Grid({
columns: [{
id: 'dateTime',
name: 'Timestamp'
}, {
id: 'host',
name: 'Host'
}, {
id: 'ipv4',
name: 'IPv4'
}, {
id: 'ipv6',
name: 'IPv6'
}],
server: {
url: "http://localhost:8080/info/zone-log",
then: data => data.map([data.dateTime, data.host, data.ipv4, data.ipv6]) 
}
}).render(document.getElementById("wrapper"));

我在JS控制台上得到以下错误:"[Grid.JS][error]:TypeError:[…]不是函数"。

有人能给我解释一下,如何正确地进行数据映射吗?

编辑

服务器响应:

curl -i http://localhost:8080/info/zone-log
HTTP/1.1 200 OK
Date: Tue, 01 Mar 2022 08:53:39 GMT
Content-Type: application/json
Transfer-Encoding: chunked
[{"dateTime":"2021-12-02 03:11:30.501","host":"master.myhost.com","ipv4":"93.215.66.14","ipv6":"2003:cc:2fff:9e4:2e91:abff:febf:d839"},{"dateTime":"2021-12-02 03:44:29.494","host":"ursa.myhost.com","ipv4":"93.203.250.190","ipv6":"n/a"}, ...}

java脚本控制台日志:

data 
Array(191) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
[0…99]
​​0: Object { dateTime: "2021-12-02 03:11:30.501", host: "master.myhost.com", ipv4: "93.215.66.14", … }
​​1: Object { dateTime: "2021-12-02 03:44:29.494", host: "ursa.myhost.com", ipv4: "93.203.250.190", … }
[Grid.js] [ERROR]: TypeError: [...] is not a function   log.ts:12:21

看起来您得到的数据不是数组。因此data.map((给出了类型错误。你能用控制台记录数据,看看会发生什么吗?

new gridjs.Grid({
columns: [{
id: 'dateTime',
name: 'Timestamp'
}, {
id: 'host',
name: 'Host'
}, {
id: 'ipv4',
name: 'IPv4'
}, {
id: 'ipv6',
name: 'IPv6'
}],
server: {
url: "http://localhost:8080/info/zone-log",
then: data => {
console.log("data", data);
return data.map([data.dateTime, data.host, data.ipv4, data.ipv6]) 
}
}
}).render(document.getElementById("wrapper"));

很可能所需的数组位于数据中的另一个对象内部。

相关内容

  • 没有找到相关文章

最新更新