gpt4 book ai didi

javascript - 如何将json文件导入到javascript中以制作图表

转载 作者:行者123 更新时间:2023-11-28 01:36:54 25 4
gpt4 key购买 nike

我想将此 test.json 文件传递​​给 javascript 文件中的 (var treeData)

{"name" : "Conrad", "info" : "tst", "children" : [
{"name" : "Rick" },
{"name" : "Lynn" },
{"name" : "John", "children": [
{"name" : "Dave", "children": [
{"name" : "Dave" },
{"name" : "Chris" }
]},
{"name" : "Chris" }
]}
]};

文件位置为:C:\Users\Bubee\Desktop\Paser Tree\codepen_DjKIa\test.json

我已经有了图形代码

// Create a svg canvas
var vis = d3.select("#viz").append("svg:svg")
.attr("width", 400)
.attr("height", 300)
.append("svg:g")
.attr("transform", "translate(40, 0)"); // shift everything to the right

// Create a tree "canvas"
var tree = d3.layout.tree()
.size([300,150]);

var diagonal = d3.svg.diagonal()
// change x and y (for the left to right tree)
.projection(function(d) { return [d.y, d.x]; });

// Preparing the data for the tree layout, convert data into an array of nodes
var nodes = tree.nodes(treeData);
// Create an array with all the links
var links = tree.links(nodes);

console.log(treeData)
console.log(nodes)
console.log(links)

var link = vis.selectAll("pathlink")
.data(links)
.enter().append("svg:path")
.attr("class", "link")
.attr("d", diagonal)

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

// Add the dot at every node
node.append("svg:circle")
.attr("r", 3.5);

// place the name atribute left or right depending if children
node.append("svg: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; })});

但是当我导入此代码时

var treeData = {};
$.ajax({
type: "GET",
url: "C:\Users\Bubee\Desktop\Paser Tree\codepen_DjKIa\test.json", //or path to JSON file
dataType: 'json'
}).done(function(data) {
treeData = data;
}).fail(function(jqXHR, textStatus) {
//catch any error here
console.log("error" );
});

只有一点

请帮帮我谢谢

最佳答案

参见http://api.jquery.com/jQuery.getJSON/ :

$.getJSON( "ajax/test.json", function( data ) {
console.log(data);
treeData = data;
//Continue here, this is asynchronous !
});

关于javascript - 如何将json文件导入到javascript中以制作图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21437652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com