如何使用javascript d3打开json文件? [英] How do I open a json file using javascript d3?

查看:227
本文介绍了如何使用javascript d3打开json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to extract elements from a JSON file using javascript, however I'm getting an error saying it can not load the JSON file.

这是我的代码如下:

<!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>

这是控制台吐出的错误:

This is the error the console is spitting out:

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服务数据。

d3.json is meant to load data through HTTP. As @Quentin said, you can set up a local server to serve the data over HTTP.

对于像这样的开发,我使用firefox,似乎更容易来到本地交叉起点请求比铬。或者,您可以使用 http://tributary.io/

For development like this I use firefox, it seems to be more permissive when it comes to local cross origin requests than chrome. Alternatively you can use http://tributary.io/

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

这篇关于如何使用javascript d3打开json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆