问题
I'm fairly new to Javascript and I'm trying to create a simple bar chart with d3.js using some data saved in the localStorage.
The data in the localStorage is acquired by the following function:
function logScore() {
var name = prompt("Please enter your name to add to the high scores list:");
var score = game.count;
var gameDate = today;
var scoreObj = { name: name, score: score, date: gameDate };
scoresArray.push(scoreObj);
window.localStorage.setItem('scoresRecord', JSON.stringify(scoresArray));
}
In a separate Javascript file, I parse the JSON object in order to store the object in an array.
var scoreData = JSON.parse(window.localStorage.getItem('scoresRecord'));
queue()
.defer(d3.json, "scoreData")
.await(makeGraph);
function makeGraph(error, scoreData) {
var ndx = crossfilter(scoreData);
var name_dim = ndx.dimension(dc.pluck('name'));
var score_dim = ndx.dimension(dc.pluck('score'));
var date_dim = ndx.dimension(dc.pluck('date'));
dc.barChart("#high-score-chart")
.width(300)
.height(150)
.margins({ top: 10, right: 50, bottom: 30, left: 50 })
.dimension(date_dim)
.group(score_dim)
.transitionDuration(500)
.x(d3.scale.ordinal())
.xUnits(dc.units.ordinal)
.xAxisLabel("Date")
.yAxisLabel("Score");
dc.renderAll();
}
Once loaded, I then try to use the data in a d3.js barchart using crossfilter, but I get the below error from the console:
https://ifd-project-simon-georgefairbairn.c9users.io/scoreData 404 (Not Found)
I think I'm loading the data correctly, but I wondered if anyone would be able to let me know if I can use crossfilter and d3.js with a JSON object stored in localStorage, and if so how?
Thanks for taking the time to read my problem - hoping someone can help!
回答1:
If you're able to get the data synchronously, loading it from local storage, then you don't need queue()
and d3.json
You should be able to do
var scoreData = JSON.parse(window.localStorage.getItem('scoresRecord'));
var ndx = crossfilter(scoreData);
The error you're getting indicates that d3.json
is trying to do an HTTP request for the data. In this case, you don't need d3.json
because JSON parsing is built into the language.
If you were using CSV data, then you might use the synchronous parse version d3.csv.parse
. There is no d3.json.parse
because it's provided directly by the language.
来源:https://stackoverflow.com/questions/51173341/crossfilter-loading-a-json-file-from-localstorage