Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

dom - Embedding csv in HTML for use with D3.js

In D3.js, one usually loads data from an external csv file. This is very efficient for large data, and avoids changing the code when the data changes.

However, there are two situations (only using small csv data) where I want to embed csv directly in an HTML page:

  • A page that can be loaded locally (i.e. from file:///), without requiring to run a local HTTP server.
  • A small jsfiddle example explaining a D3.js question for use on stackoverflow.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is the solution I have come up with, using the example from the D3.js API.

Embedding the csv data:

<pre id="csvdata">
    Year,Make,Model,Length
    1997,Ford,E350,2.34
    2000,Mercury,Cougar,2.38
</pre>

Hidding the raw data on the page:

#csvdata {
    display: none;
}

Parsing it:

var raw = d3.select("#csvdata").text();
var parsed = d3.csv.parse(raw);

Optionally, show the result:

d3.select("#parsed").text(JSON.stringify(parsed));
// Assuming <div id="parsed"></div> somewhere on the page

If think this is flawed, or if you have a more elegant solution, I will gladly accept your answer!

EDIT: see it in action in this fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...