【发布时间】:2018-06-28 09:39:33
【问题描述】:
我刚刚在d3.js上开始了一个任务,我在网上修改了一点这个脚本,请看下面的最后一个。
目前下面的最后一部分可以用于读取本地文件,而目前我有自己的 json 对象从 ajax 返回,由后端处理。
success function(data){ }
请问在这种情况下,我该如何使用 d3.json?因为下面的部分只能用于从 json 文件中读取数据,而不是从 json 字符串或 json 对象中读取数据。 是否提供了可能的功能来替换
d3.json("miserables.json", function(error, graph) { if (error) throw 错误; ... }
因为这只能处理文件,而不能处理输入的json字符串或对象?
d3.json("miserables.json", function(error, graph) {
if (error) throw error;
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line")
/*.attr("stroke-width", function(d) { return Math.sqrt(d.value); })*/;
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 3)
/*.attr("fill", function(d) { return color(d.group); })*/
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
node.append("title")
.text(function(d) { return d.id; });
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function ticked() {
link
.attr("x1", function(d) { return (d.source.x); })
.attr("y1", function(d) { return (d.source.y); })
.attr("x2", function(d) { return (d.target.x); })
.attr("y2", function(d) { return (d.target.y); });
node
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
});
我的 json 对象是这样的
{"nodes": [
{"id": "Myriel"},
{"id": "Napoleon"},
{"id": "Mlle.Baptistine"},
{"id": "Mme.Magloire"},
{"id": "CountessdeLo"},
{"id": "Geborand"},
{"id": "Champtercier"},
{"id": "Cravatte"},
{"id": "Count"},
{"id": "OldMan"},
{"id": "Labarre"},
{"id": "Valjean"},
{"id": "Marguerite"},
{"id": "Mme.deR"}
]}
ThQ!!!!
【问题讨论】:
标签: javascript json d3.js