2014-02-21 64 views
0

在我正在處理的應用程序中,我們需要使用D3顯示可摺疊樹形圖。將要放入此圖的數據不會存儲在文件中,而是存儲在數據庫中,並通過對rest服務的Ajax調用傳遞給JavaScript,並以JSON形式存儲到var中。使用變量中的數據加載D3可摺疊樹

Ajax調用返回正確的數據,我將它存儲到var json_data。這裏是阿賈克斯代碼:

var json_data; 

jQuery.getJSON("/ux/resources/graph", function(json){ 
    json_data = json; 
    init(); //This calls the entire D3 setup 
}); 

如上所示,我等待數據返回到呈現D3之後。

這是我的init方法。

function init(){ 
    d3.json(json_data, function(error, json) { 
     root = json; 
     root.x0 = height/2; 
     root.y0 = 0; 

     function collapse(d) { 
      if (d.children) { 
       d._children = d.children; 
       d._children.forEach(collapse); 
       d.children = null; 
      } 
     } 

     root.children.forEach(collapse); 
     update(root); 
    }); 

    d3.select(self.frameElement).style("height", "800px"); 
}; 

如何讓D3能夠識別json_data輸入並從中創建圖形?

回答

2

d3.json()jQuery.getJSON做的事情基本相同:它從一個url加載json。所以如果你已經加載了jQuery,那麼從init()調用d3.json()是不必要的。除此之外,d3.json()的第一個參數應該是數據的網址,而不是您顯示的數據本身。

也許是合適的事情做的是拋棄了jQuery getJSON()呼叫並調用初始化馬上(和傳遞正確的URL到d3.json()

init();// no $.getJSON() needed 

function init(){ 
    d3.json("/ux/resources/graph", function(error, json) { 
    ... 

相反,如果你願意來加載通過jQuery的數據,然後只需加載的數據傳遞到init方法,並跳過d3.json()電話:

jQuery.getJSON("/ux/resources/graph", function(json){ 
    init(json); //This calls the entire D3 setup 
}); 

function init(json) { // json is passed in 
    root = json; 
    // Notice that here's you're modifying the loaded json. 
    // Probably fine, but be aware of it. 
    root.x0 = height/2; 
    root.y0 = 0; 
    ... 
+1

meetamit的建議是恕我直言現場有一對夫婦在這裏樹形圖的例子([http://www.d3noob.org/ 2014/01 /樹diagrams- in-d3js_11.html](http://www.d3noob.org/2014/01/tree-diagrams-in-d3js_11.html)),包括一個使用d3.json – d3noob

+0

如果我從post請求中獲得數據? –

+0

@ 7H3IN5ID3R當然,爲什麼不呢? – meetamit