2014-06-25 22 views
0

我想從Web API(JSON格式)導入數據並將其用於可視化。正如你在下面的代碼中看到的那樣,我已經實現了一切,它幾乎可以工作。JavaScript,使用D3導入Web API

問題:dataExportdata不一樣。爲什麼?如何更改我的代碼,使dataExportdata一樣?

代碼:

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); 

CONSOLE.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 

謝謝!

回答

0

因爲您將整個解析過程存儲在dataStore變量中,而數據變量只包含您在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); 
     } 
}); 

數據存儲中應該包含有用的結果

編輯:訪問它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); 
+0

謝謝,這是有道理的。但是在這種情況下,'dataStore'沒有在d3.json(...)之外定義;我認爲,它必須是出口。 – Kevin

+0

然後你可以在你的腳本開始時聲明它是一個全局變量,並將'dataStore = data;'放在適當的位置 - 在答案中看到編輯 –

+0

Perfect。謝謝! – Kevin