Javascript 用变量中的数据加载D3可折叠树
在我正在开发的应用程序中,我们需要使用D3显示一个可折叠的树形图。将放入此图中的数据不存储在文件中,而是存储在数据库中,通过对rest服务的Ajax调用传递给JavaScript,并以JSON形式存储到var中 Ajax调用返回正确的数据,我将其存储到var json_数据中。以下是Ajax代码:Javascript 用变量中的数据加载D3可折叠树,javascript,jquery,ajax,json,d3.js,Javascript,Jquery,Ajax,Json,D3.js,在我正在开发的应用程序中,我们需要使用D3显示一个可折叠的树形图。将放入此图中的数据不存储在文件中,而是存储在数据库中,通过对rest服务的Ajax调用传递给JavaScript,并以JSON形式存储到var中 Ajax调用返回正确的数据,我将其存储到var json_数据中。以下是Ajax代码: var json_data; jQuery.getJSON("/ux/resources/graph", function(json){ json_data = json; init
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_数据输入并从中创建图形?D3.json()
的作用与jQuery.getJSON
的作用基本相同:它从url加载json。因此,如果您已经用jQuery加载了init()
,那么从init()调用d3.json()
是不必要的。除此之外,第一个参数到d3.json()
应该是数据的URL,而不是您所显示的数据本身
可能要做的适当的事情是放弃jQuerygetJSON()
调用,直接调用init(并将正确的url传递到d3.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;
...
meetamit的建议就在IMHO上。这里有两个树形图示例(),其中一个使用了d3.json如果我从post请求中获得数据会怎么样?@7H3IN5ID3R当然,为什么不呢?只需在Query.getJSON(“/ux/resources/graph”,function(json){?@7H3IN5ID3RjQuery.post(/ux/resources/graph,…)
中传递url即可。请参见
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;
...