JavaScript、Web API 使用 D3(数据驱动文档)导入

问题描述 投票:0回答:1

我想从 Web API(JSON 格式)导入数据并将其用于可视化。正如您在下面的代码中看到的,我已经实现了所有内容并且它(几乎)有效。

问题:

dataExport
data
不同。为什么?我如何更改我的代码,使
dataExport
data
相同?

代码:

var dataExport = d3.json("http://link to the Server...", function(error, data){
            if(error) {
                console.log(error);
            } else {
                console.log(data);

                console.log(data.collection.items);
            }
});
        
console.log(dataExport);

控制台.log(数据);

Object {collection: Object}
collection: Object
href: "http://link to the Server..."
items: Array[50]
links: Array[1]
queries: Array[1]
version: "1.0"
__proto__: Object
__proto__: Object

Console.log(数据导出);

Object {header: function, mimeType: function, responseType: function, response: function, get: function…}
abort: function (){return c.abort(),i}
get: function (){return i.send.apply(i,[n].concat(Qo(arguments)))}
header: function (n,t){return n=(n+"").toLowerCase(),arguments.length<2?a[n]:(null==t?delete a[n]:a[n]=t+"",i)}
mimeType: function (n){return arguments.length?(t=null==n?null:n+"",i):t}
on: function (){var r=e.apply(t,arguments);return r===t?n:r}
post: function (){return i.send.apply(i,[n].concat(Qo(arguments)))}
response: function (n){return e=n,i}
responseType: function (n){return arguments.length?(s=n,i):s}
send: function (e,r,u){if(2===arguments.length&&"function"==typeof r&&(u=r,r=null),c.open(e,n,!0),null==t||"accept"in a||(a.accept=t+",*/*"),c.setRequestHeader)for(var l in a)c.setRequestHeader(l,a[l]);return null!=t&&c.overrideMimeType&&c.overrideMimeType(t),null!=s&&(c.responseType=s),null!=u&&i.on("error",u).on("load",function(n){u(null,n)}),o.beforesend.call(i,c),c.send(null==r?null:r),i}
__proto__: Object
javascript json d3.js webapi
1个回答
0
投票

因为您将整个解析过程存储在 dataStore 变量中,而 data 变量仅包含您在 d3.json 中调用的数据 - 正如它应该的那样。

您不需要使用其他变量,所以只需尝试

d3.json("http://link to the Server...", function(error, dataStore){
        if(error) {
            console.log(error);
        } else {
            console.log(dataStore);

            console.log(dataStore.collection.items);
        }
});

dataStore 应包含想要的结果

编辑:在 d3.json 之外访问它

var dataStore; //declare a global variable somewhere at the beginning of your script

然后

d3.json("http://link to the Server...", function(error, data){
    if(error) {
        console.log(error);
    } else {
        dataStore=data;
    }
});

console.log(dataStore);
console.log(dataStore.collection.items);
© www.soinside.com 2019 - 2024. All rights reserved.