简体   繁体   中英

How do I open a json file using javascript d3?

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.

This is what my code looks like:

<!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 is meant to load data through HTTP. As @Quentin said, you can set up a local server to serve the data over HTTP.

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/

Example with your code: http://tributary.io/inlet/5776228

Cross origin requests are only supported for HTTP.

Load the site over HTTP. Install a web server (such as Apache HTTPD or Lighttpd) if you need to.

Alternatively to installing web server or using 3rd party online environments you can just use different code editor - Brackets . It offers feature called "Live Preview". I just hit same error Uncaught XMLHttpRequest with similar code, can confirm code works perfectly in Brackets.

Brackets works directly with your browser to push code edits instantly, so your browser preview is always up to date while you're coding — no page reloads needed. In order to keep your current web browsing unaffected, Brackets Live Preview opens an additional copy of Chrome using a separate Chrome profile. // From How to Use Brackets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM