1. Basic commands for loading data
D3 provides methods to load different data types, such as D3.text (), D3.xml (), D3.json (), D3.csv (), and d3.html ().
<!DOCTYPE HTML><Head> <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /> <title>Test</title> <Scripttype= "Text/javascript"src= "D3.js"></Script> </Head> <Body> <DivID= "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>
The above code is loaded with a CSV file and a JSON file, the function is actually a callback, of course, the error if you do not need to save.
2. Using Server to server file
Testing the above code in Chrome will cause the following error:
XMLHttpRequest cannot load file:/cities.csv. Cross origin requests is only supported for protocol schemes:http, data, Chrome, chrome-extension, HTTPS, Chrome-extensi On-resource.
Uncaught networkerror:failed to execute ' send ' in ' XMLHttpRequest ': Failed to load
This is because the security mechanism prohibits cross origin request and does not allow direct read of local files, so we need a webserver to server our data.
The following commands can be executed in CMD in the window environment (provided that NPM is installed)
Install http-serverhttp-server C:\D3Test
In this way, we start a server, the browser accesses the http://localhost:8080/index.html, and then we can see the loaded data in the console.
An array of JSON objects returned by D3.csv () and D3.json load data.
3. Asynchronous loading
Modify the code in the script section above as follows:
Console.log ("before CSV"); D3.csv (function(data) {Console.log (data)}); Console.log ("before JSON"); D3.json ("Flare.json",function(error,data2) {console.log (Error, DATA2)});
The results of the implementation are as follows:
You can see that the actual execution order and the order in the code do not match. The reason is that d3.csv () and D3.json are loading data asynchronously, and loading the data often takes more time than other operations. Also for this reason, an error occurs if data requests are made between data load completion.
There are two ways we can bypass the problem of asynchronous loading
The first: Nesting of data loading and processing
function (data) {dosomethingwithdata (data)});
The second is to use some helper library (Queue.js) to implement the corresponding operation after the data load is complete.
Reference: D3.js in Action
D3.js loading CSV and JSON data