在我正在开发的应用程序中,我们需要使用 D3 显示可折叠的树形图。将放入该图中的数据不会存储在文件中,而是存储在数据库中,通过对 Rest 服务的 Ajax 调用传递给 JavaScript,并以 JSON 形式存储在 var 中。
Ajax 调用返回正确的数据,我将其存储到 var json_data。这是 Ajax 代码:
var json_data;
jQuery.getJSON("/ux/resources/graph", function(json){
json_data = json;
init(); //This calls the entire D3 setup
});
如上所示,我等待数据返回后渲染D3。
这是我的初始化方法。
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 输入并从中创建图表?
最佳答案
d3.json()
的作用与 jQuery.getJSON
的作用基本相同:它从 url 加载 json。因此,如果您已经使用 jQuery 加载了 d3.json()
,则无需从 init()
调用它。除此之外,d3.json()
的第一个参数应该是数据的 URL,而不是您显示的数据本身。
可能正确的做法是放弃 jQuery getJSON()
调用并立即调用 init (并将正确的 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;
...
关于javascript - 使用变量中的数据加载 D3 可折叠树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21946768/