javascript – D3不会加载树形图

我正在尝试使用带有JSON文件的D3来创建和显示树图.很简单,只是尝试D3的乐趣.但是,在我将我的tree.js放在一起并运行脚本后,我得到一个空白页面.控制台说

XMLHttpRequest cannot load file:///Users/aczre/Desktop/d3TestApp/shreleases.json.
Cross origin requests are only supported for HTTP.

Uncaught TypeError: Cannot read property 'children' of null d3.v2.js:6081
d3_layout_hierarchyChildren d3.v2.js:6081
 recurse d3.v2.js:5990
 hierarchy d3.v2.js:6033
 tree d3.v2.js:6384
 object.nodes d3.v2.js:6074
 (anonymous function) tree.js:17
 d3.json d3.v2.js:514
 ready d3.v2.js:504
 d3.xhr.req.onreadystatechange d3.v2.js:497
 d3.xhr d3.v2.js:500
 d3.text d3.v2.js:510
 d3.json d3.v2.js:513
 (anonymous function) tree.js:16

Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101 d3.v2.js:500
 d3.xhr d3.v2.js:500
 d3.text d3.v2.js:510
 d3.json d3.v2.js:513
 (anonymous function) tree.js:16

不知道我做错了什么……这是我的tree.js

var width = 960,
    height = 2000;

var tree = d3.layout.tree()
    .size([height, width - 160]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var vis = d3.select("#chart").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(40, 0)");

d3.json("shreleases.json", function(json) { // Line 16
  var nodes = tree.nodes(json);

  var link = vis.selectAll("path.link")
  .data(tree.links(nodes))
.enter().append("path")
  .attr("class", "link")
  .attr("d", diagonal);

  var node = vis.selectAll("g.node")
      .data(nodes)
     .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

  node.append("circle")
      .attr("r", 4.5);

  node.append("text")
      .attr("dx", function(d) { return d.children ? -8 : 8; })
      .attr("dy", 3)
      .attr("text-anchor", function(d) { return d.children ? "end" : "start"; })
      .text(function(d) { return d.name; });
});

我试图坚持D3网站上列出的例子,https://github.com/mbostock/d3/wiki/Gallery
但我不确定我是否完全理解语法.

解决方法:

您可能需要从Web服务器发出JSON文件的请求.该错误消息抱怨它不是http请求,因为您的文件存储在本地.

您可以将JSON文件丢弃到Web主机上(如果有的话).或者您可以使用类似WAMP的东西创建本地服务器设置.

上一篇:苹果mac窗口速调辅助工具:Magnet


下一篇:HashMap和TreeMap的区别