使用变量中的数据加载D3可折叠树

科雷

在我正在开发的应用程序中,我们需要使用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。因此d3.json()init()如果您已经使用jQuery进行了调用,则从调用是不必要的。除此之外,第一个参数d3.json()应该是数据的URL,而不是您所显示的数据本身。

大概合适的做法是抛弃jQuerygetJSON()调用,然后立即调用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;
  ...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章