如何使用 javascript d3 打开 json 文件?

2023-11-29

我正在尝试使用 javascript 从 JSON 文件中提取元素,但是收到一条错误消息,指出它无法加载 JSON 文件。

这就是我的代码的样子:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>D3 Tutorial</title>
    <script src="http://d3js.org/d3.v3.min.js">  </script>
</head>
<body>
    <script>

        d3.json("mydata.json", function(data) {

            var canvas = d3.select("body").append("svg")
                .attr("width", 500)
                .attr("height", 500)

            canvas.selectAll("rect")
                .data(data)
                .enter()
                    .append("rect")
                    .attr("width", function (d) { return d.age * 10;})
                    .attr("height", 48)
                    .attr("y", function (d,i) { return i * 50; })
                    .attr("fill", "blue");

        })

    </script>
</body>
</html>

这是控制台吐出的错误:

XMLHttpRequest cannot load file:///C:/locationoffile..../mydata.json. Cross origin requests are only supported for HTTP. d3.v3.min.js:1
Uncaught TypeError: Cannot read property 'length' of null d3.v3.min.js:3
Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101 d3.v3.min.js:1

d3.json 旨在通过 HTTP 加载数据。正如 @Quentin 所说,您可以设置本地服务器来通过 HTTP 提供数据。

对于这样的开发,我使用 Firefox,它似乎比 Chrome 更宽容地处理本地跨源请求。或者你可以使用http://tributary.io/

您的代码示例:http://tributary.io/inlet/5776228

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 javascript d3 打开 json 文件? 的相关文章

随机推荐