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

标签 javascript html json dom

我正在尝试使用 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

关于javascript - 如何使用 javascript d3 打开一个 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17094487/

相关文章:

javascript - 我怎样才能让 JSSOR 改变它的纵横比?

html - 具有相对定位的 CSS div 在 IE 中无法正常工作

javascript - PIXI.js - 滚动背景网格

PHP json_encode 类私有(private)成员

javascript - :touch CSS pseudo-class or something similar?

javascript - 如何在 javascript 中使用 grails ${createLink}

php - 通过php获取html5上传的有值(value)的图片

c# - 将 JSON 对象传递到列表中

java - JSON "flat"使用 Java 序列化

javascript - 同一个函数参数可以接受不同的数据类型吗?