The core

D3 provides its own system for making requests, which is found in the d3-request module. It uses XMLHttpRequests via the humble d3.xhr(), the manual way of issuing an XHR request.

It takes a URL and an optional callback. If supplied with a callback, it will immediately trigger the request and receive the data as an argument once the request finishes.

If there's no callback, we get to tweak the request -- everything from the headers to the request method -- making the request once ready.

To make a request, you might have to write the following code:

   let xhr = d3.xhr('http://www.example.com/test.json'); 
xhr.mimeType('application/json');
xhr.header('User-Agent', 'SuperAwesomeBrowser');
xhr.on('load', function (request) { ... });
xhr.on('error', function (error) { ... });
xhr.on('progress', function () { ... });
xhr.send('GET');

This will send a GET request expecting a JSON response and tell the server that we're a web browser named SuperAwesomeBrowser. One way to shorten this is by defining a callback immediately, but then you can't define custom headers or listen for other request events.

Another way is D3 convenience functions. They include the following:

d3.text to import a text file as a string:

d3.text('/data/transcript.txt', (error, text) => { 
console.log(text);
});

d3.csv to load a comma-separated value spreadsheet. Use d3.tsv for tab-separated:

d3.csv('/data/finance_data.csv', (error, data) => { 
console.log(data);
});

d3.json to load a JSON file:

d3.json('http://www.aendrew.com/hello.json', (error, data) => { 
console.log(data);
});

d3.xml to load in an XML file:

d3.xml('/probably/made/by/java.xml', (error, data) => { 
console.log(data);
});

Note that you don't have to use any of these if you've gotten your data some other way; for instance, if you've loaded a CSV file as a string variable, you can use d3.csvParse from the d3-dsv module to turn that into an object or array. Similarly, you can use the browser's built-in JSON.parse() to convert a JSON string into a usable object or DOMParser for XML.

Callbacks are used for flow control in all of the mentioned convenience methods, which can be annoying if you need to make multiple requests. Let's talk about that now.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset