Javascript 如何使用实时JSON数据更新D3.js气泡图?

Javascript 如何使用实时JSON数据更新D3.js气泡图?,javascript,json,ajax,d3.js,Javascript,Json,Ajax,D3.js,我正在学习d3,并尝试将静态气泡图转换为动态版本,在JSON更改时删除/添加气泡 我想每5秒读取一次JSON文件并更新气泡图。我尝试将setInterval()与以下代码一起使用,但不起作用 var inter = setInterval(function() { updateData(); }, 5000); function updateData() { d3.json("sample.json", function(error, data) { if (error) th

我正在学习d3,并尝试将静态气泡图转换为动态版本,在JSON更改时删除/添加气泡

我想每5秒读取一次JSON文件并更新气泡图。我尝试将
setInterval()
与以下代码一起使用,但不起作用

var inter = setInterval(function() {
  updateData();
}, 5000);

function updateData() {
  d3.json("sample.json", function(error, data) {
    if (error) throw error;

    //take in the json file
   root = d3.hierarchy(classes(data))
        .sum(function(d) { return d.value; })
        .sort(function(a, b) { return b.value - a.value; });
   console.log(root);
   bubble(root);

   node = svg.selectAll(".node")
       .data(root.children);

   node.exit().remove();

   //add new things into the file
   node.enter().append("g")
   .attr("class", "node")

   node.append("title")
       .text(function(d) { return d.data.className + ": " + format(d.value); });

   node.append("circle")
       .attr("r", function(d) { return d.r; })
       .style("fill", function(d) {
         return color(d.data.packageName);
       });

   node.append("text")
       .attr("dy", ".3em")
       .style("text-anchor", "middle")
       .text(function(d) { return d.data.className.substring(0, d.r / 3); });
  });
}
//==============================================================================
// updates end here

d3.select(self.frameElement).style("height", diameter + "px");

// Helper function definations
// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
  var classes = [];

  function recurse(name, node) {
    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
    else classes.push({packageName: name, className: node.name, value: node.size});
  }

  recurse(null, root);
  return {children: classes};
}
我尝试将root打印到控制台,但没有更改

此外,我对AJAX知之甚少,是否有必要使用AJAX更新JSON数据


如果是这样,我应该如何使用POST方法更新整个JSON文件?

可能是浏览器缓存。 试试这个:

d3.json("sample.json?v="+Date.now(), function(error, data) { ...

看起来您正在检索一个内容不变的文件

d3.json("sample.json", [...]
如果
sample.json
没有改变,您的数据将保持不变。您需要一些服务器端处理来在该位置生成新的json文件,或者需要使用某种API来检索动态值(可能是从数据库中)。您拥有的代码可以使用这些数据