Reputation: 11
I'm fairly new to both Javascript and D3, and I've been trying to try the examples from the website myself.
I used the following for the JS/HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style type="text/css">
</style>
<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("y", function (d, i) { return i * 50; })
.attr("fill", "blue")
})
</script>
</body>
</html>
and for my "mydata.json" I am using:
[
{"name": "Maria", "age": 30},
{"name": "Fred", "age": 50},
{"name": "Jason", "age": 12}
]
Every-time I try and run it, it doesn't have the same result as the examples on the d3 examples page. Please help, I am try to figure out how d3 works, and I am quite a novice programmer.
Upvotes: 1
Views: 3208
Reputation: 2461
As stated here, the problem stems from a security restriction when using file://
style URLs.
One solution, other than embedding the JSON object in your .js
file, is to load the files via http. This is easily achieved using nodejs!
Follow these steps:
cd
to your demo folder.npm install Express
. This will install the Express web-server components into the .\node_modules
folder.node .\web-server.js
on the command-line.htdocs
then move your .html
, .js
, and .json
files, and any other web assets into it. This will be the root folder of your web site.http://localhost:9999/[your-html-file].html
, where [your-html-file] is replaced with the actual filename.web-server.js
var server_port = 9999;
var application_root = __dirname + "\\htdocs",
express = require("express"),
path = require("path");
var app = express();
app.use(express.static(application_root));
app.use(app.router);
app.listen(server_port);
console.log("Web server listening on port " + server_port + ".");
This should get you past the issue of loading the .json
file. In fact, it's useful whenever you need a light-weight web server to test code with.
Upvotes: 1
Reputation: 15325
It seems like you have to set the height
attribute to display something.
A good way of debugging this kind of problem is to first make everything work without the json call. To do so I would recommend you to use the chrome javascript console to display errors and the chrome inspector to see the html code.
data = [{
"name": "Maria",
"age": 30
}, {
"name": "Fred",
"age": 50
}, {
"name": "Jason",
"age": 12
}]
//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", "20px")
.attr("y", function (d, i) {
return i * 50;
})
.attr("fill", "blue")
//})
jsFiddle: http://jsfiddle.net/chrisJamesC/LX9BF/
Upvotes: 1