Crossfilter-从localStorage加载JSON文件 [英] Crossfilter - Loading a JSON file from localStorage

查看:69
本文介绍了Crossfilter-从localStorage加载JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java语言还很陌生,我正尝试使用保存在localStorage中的一些数据使用d3.js创建一个简单的条形图.

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.

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));
}

在一个单独的Javascript文件中,我解析JSON对象,以便将该对象存储在数组中.

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();
}

一旦加载,我随后尝试使用Crossfilter在d3.js条形图中使用数据,但从控制台收到以下错误:

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(未找到)

我认为我正确加载了数据,但是我想知道是否有人可以让我知道是否可以对存储在localStorage中的JSON对象使用crossfilter和d3.js,如果可以,怎么办?

感谢您抽出宝贵的时间阅读我的问题-希望有人可以提供帮助!

Thanks for taking the time to read my problem - hoping someone can help!

推荐答案

如果能够同步获取数据,并从本地存储中加载数据,则不需要 queue() d3.json

If you're able to get the data synchronously, loading it from local storage, then you don't need queue() and d3.json

您应该能够做到

var scoreData = JSON.parse(window.localStorage.getItem('scoresRecord'));
var ndx = crossfilter(scoreData);

您收到的错误表明 d3.json 正在尝试对数据进行HTTP请求.在这种情况下,您不需要 d3.json ,因为该语言内置了JSON解析功能.

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.

如果您使用的是CSV数据,则可以使用同步解析版本 d3.csv.parse .没有 d3.json.parse ,因为它是由语言直接提供的.

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.

这篇关于Crossfilter-从localStorage加载JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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