D3.js加载csv和json数据

1.加载数据的基本命令

D3提供了方法能够对不一样的数据类型进行加载,好比d3.text(), d3.xml(), d3.json(), d3.csv(), 和d3.html().javascript

<!DOCTYPE html>
<head>
    <meta  http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>test</title>    
    <script type="text/javascript" src="d3.js"></script>    
</head>    
<body>
    <div id="borderdiv"> 123</div>      
</body>
    
<script>      
    d3.csv("cities.csv", function(data) {console.log(data)});
    d3.json("flare.json",function(error,data2) {console.log(error, data2)});
</script>

</html>

上面的代码中加载了一个csv文件和一个json文件,function实际是一个callback,固然其中的error若是不须要的话可省去。html

 

2.使用server来server file

在chrome中测试上面的代码会出现如下错误:java

XMLHttpRequest cannot load file:/cities.csv. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.node

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load web

这是由于安全机制禁止了cross origin request,不容许直接读取本地文件, 因此咱们须要一个webserver来server咱们的数据。chrome

window环境下能够在cmd中执行以下命令(前提是安装了npm)npm

nmp install http-server
http-server C:\D3Test

这样,咱们便启动了一个server, 浏览器访问http://localhost:8080/index.html,而后即可以在console中看到加载的数据。json

d3.csv()和d3.json加载数据返回的一个json对象的数组。数组

 3.异步加载

将上面的script部分代码修改以下:浏览器

 console.log("before csv ");
 d3.csv("cities.csv", function(data) {console.log(data)});
 console.log("before json");
 d3.json("flare.json",function(error,data2) {console.log(error, data2)});

执行结果以下:

能够看到,实际执行顺序和代码中顺序并不符合。缘由是d3.csv()和d3.json是异步加载数据的,而加载数据每每比其余操做须要更多的时间。也是因为这样缘由,若是在数据加载完成之间进行数据请求将出现错误。

咱们有两种方法能够绕开异步加载的问题

第一种:将数据加载和处理嵌套在一块儿

d3.csv("somefiles.csv", function(data) {doSomethingWithData(data)});

第二种:使用一些helper类库(queue.js)来实如今数据加载完成后出发相应的操做。

 

参考:D3.js in Action

相关文章
相关标签/搜索