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

标签 javascript jquery ajax json d3.js

在我正在开发的应用程序中,我们需要使用 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/

相关文章:

asp.net - 从数据库中删除而不回发 - 想要为删除的消失项目设置动画

jquery - 如何调整 jQuery 按钮的大小?

Javascript - 从日期格式中删除秒数和 GMT

javascript - Prototype.js 1.4.0 抛出 'Refused to set unsafe header "连接“”错误

javascript - 无法在 typescript 中调用 svgdotjs rect 方法

jquery - 如何使用来自另一个url的新数据重新加载jqxGrid数据

PHP 拆分字符串并插入 MySQL

javascript - 从 AJAX 响应程序脚本调用 PHP 类

jquery - 此页面上的脚本导致 Internet Explorer 运行缓慢

javascript - 检查互联网连接的最佳方法是什么