• Stars
    star
    109
  • Rank 319,077 (Top 7 %)
  • Language
    JavaScript
  • License
    BSD 3-Clause "New...
  • Created over 9 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A convenient alternative to XMLHttpRequest.

d3-request

This module is deprecated as of D3 5.0; please use d3-fetch instead.

This module provides a convenient alternative to XMLHttpRequest. For example, to load a text file:

d3.text("/path/to/file.txt", function(error, text) {
  if (error) throw error;
  console.log(text); // Hello, world!
});

To load and parse a CSV file:

d3.csv("/path/to/file.csv", function(error, data) {
  if (error) throw error;
  console.log(data); // [{"Hello": "world"}, …]
});

To post some query parameters:

d3.request("/path/to/resource")
    .header("X-Requested-With", "XMLHttpRequest")
    .header("Content-Type", "application/x-www-form-urlencoded")
    .post("a=2&b=3", callback);

This module has built-in support for parsing JSON, CSV and TSV; in browsers, but not in Node, HTML and XML are also supported. You can parse additional formats by using request or text directly.

Installing

If you use NPM, npm install d3-request. Otherwise, download the latest release. You can also load directly from d3js.org, either as a standalone library or as part of D3 4.0. AMD, CommonJS, and vanilla environments are supported. In vanilla, a d3 global is exported:

<script src="https://d3js.org/d3-collection.v1.min.js"></script>
<script src="https://d3js.org/d3-dispatch.v1.min.js"></script>
<script src="https://d3js.org/d3-dsv.v1.min.js"></script>
<script src="https://d3js.org/d3-request.v1.min.js"></script>
<script>

d3.csv("/path/to/file.csv", callback);

</script>

API Reference

# d3.request(url[, callback]) <>

Returns a new request for specified url. If no callback is specified, the returned request is not yet sent and can be further configured. If a callback is specified, it is equivalent to calling request.get immediately after construction:

d3.request(url)
    .get(callback);

If you wish to specify a request header or a mime type, you must not specify a callback to the constructor. Use request.header or request.mimeType followed by request.get instead. See d3.json, d3.csv, d3.tsv, d3.html and d3.xml for content-specific convenience constructors.

# request.header(name[, value]) <>

If value is specified, sets the request header with the specified name to the specified value and returns this request instance. If value is null, removes the request header with the specified name instead. If value is not specified, returns the current value of the request header with the specified name. Header names are case-insensitive.

Request headers can only be modified before the request is sent. Therefore, you cannot pass a callback to the request constructor if you wish to specify a header; use request.get or similar instead. For example:

d3.request(url)
    .header("Accept-Language", "en-US")
    .header("X-Requested-With", "XMLHttpRequest")
    .get(callback);

Note: this library does not set the X-Requested-With header to XMLHttpRequest by default. Some servers require this header to mitigate unwanted requests, but the presence of the header triggers CORS preflight checks; if necessary, set this header before sending the request.

# request.mimeType([type]) <>

If type is specified, sets the request mime type to the specified value and returns this request instance. If type is null, clears the current mime type (if any) instead. If type is not specified, returns the current mime type, which defaults to null. The mime type is used to both set the "Accept" request header and for overrideMimeType, where supported.

The request mime type can only be modified before the request is sent. Therefore, you cannot pass a callback to the request constructor if you wish to override the mime type; use request.get or similar instead. For example:

d3.request(url)
    .mimeType("text/csv")
    .get(callback);

# request.user([value]) <>

If value is specified, sets the user name for authentication to the specified string and returns this request instance. If value is not specified, returns the current user name, which defaults to null.

# request.password([value]) <>

If value is specified, sets the password for authentication to the specified string and returns this request instance. If value is not specified, returns the current password, which defaults to null.

# request.timeout([timeout]) <>

If timeout is specified, sets the timeout attribute of the request to the specified number of milliseconds and returns this request instance. If timeout is not specified, returns the current response timeout, which defaults to 0.

# request.responseType([type]) <>

If type is specified, sets the response type attribute of the request and returns this request instance. Typical values are: ​ (the empty string), arraybuffer, blob, document, and text. If type is not specified, returns the current response type, which defaults to ​.

# request.response(value) <>

Sets the response value function to the specified function and returns this request instance. The response value function is used to map the response XMLHttpRequest object to a useful data value. See the convenience methods json and text for examples.

# request.get([data][, callback]) <>

Equivalent to request.send with the GET method:

request.send("GET", data, callback);

# request.post([data][, callback]) <>

Equivalent to request.send with the POST method:

request.send("POST", data, callback);

# request.send(method[, data][, callback]) <>

Issues this request using the specified method (such as GET or POST), optionally posting the specified data in the request body, and returns this request instance. If a callback is specified, the callback will be invoked asynchronously when the request succeeds or fails. The callback is invoked with two arguments: the error, if any, and the response value. The response value is undefined if an error occurs. This is equivalent to:

request
    .on("error", function(error) { callback(error); })
    .on("load", function(xhr) { callback(null, xhr); })
    .send(method, data);

If no callback is specified, then "load" and "error" listeners should be registered via request.on.

# request.abort() <>

Aborts this request, if it is currently in-flight, and returns this request instance. See XMLHttpRequest’s abort.

# request.on(type[, listener]) <>

If listener is specified, sets the event listener for the specified type and returns this request instance. If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. If listener is null, removes the current event listener for the specified type (if any) instead. If listener is not specified, returns the currently-assigned listener for the specified type, if any.

The type must be one of the following:

  • beforesend - to allow custom headers and the like to be set before the request is sent.
  • progress - to monitor the progress of the request.
  • load - when the request completes successfully.
  • error - when the request completes unsuccessfully; this includes 4xx and 5xx response codes.

To register multiple listeners for the same type, the type may be followed by an optional name, such as load.foo and load.bar. See d3-dispatch for details.

# d3.csv(url[[, row], callback]) <>

Returns a new request for the CSV file at the specified url with the default mime type text/csv. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("text/csv")
    .response(function(xhr) { return d3.csvParse(xhr.responseText, row); });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("text/csv")
    .response(function(xhr) { return d3.csvParse(xhr.responseText, row); })
    .get(callback);

An optional row conversion function may be specified to map and filter row objects to a more-specific representation; see dsv.parse for details. For example:

function row(d) {
  return {
    year: new Date(+d.Year, 0, 1), // convert "Year" column to Date
    make: d.Make,
    model: d.Model,
    length: +d.Length // convert "Length" column to number
  };
}

The returned request exposes an additional request.row method as an alternative to passing the row conversion function to d3.csv, allowing you to configure the request before sending it. For example, this:

d3.csv(url, row, callback);

Is equivalent to this:

d3.csv(url)
    .row(row)
    .get(callback);

# d3.html(url[, callback]) <>

Returns a new request for the HTML file at the specified url with the default mime type text/html. The HTML file is returned as a document fragment. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("text/html")
    .response(function(xhr) { return document.createRange().createContextualFragment(xhr.responseText); });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("text/html")
    .response(function(xhr) { return document.createRange().createContextualFragment(xhr.responseText); })
    .get(callback);

HTML parsing requires a global document and relies on DOM Ranges, which are not supported by JSDOM as of version 8.3; thus, this method is supported in browsers but not in Node.

# d3.json(url[, callback]) <>

Returns a new request to get the JSON file at the specified url with the default mime type application/json. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("application/json")
    .response(function(xhr) { return JSON.parse(xhr.responseText); });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("application/json")
    .response(function(xhr) { return JSON.parse(xhr.responseText); })
    .get(callback);

# d3.text(url[, callback]) <>

Returns a new request to get the text file at the specified url with the default mime type text/plain. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("text/plain")
    .response(function(xhr) { return xhr.responseText; });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("text/plain")
    .response(function(xhr) { return xhr.responseText; })
    .get(callback);

# d3.tsv(url[[, row], callback]) <>

Returns a new request for a TSV file at the specified url with the default mime type text/tab-separated-values. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("text/tab-separated-values")
    .response(function(xhr) { return d3.tsvParse(xhr.responseText, row); });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("text/tab-separated-values")
    .response(function(xhr) { return d3.tsvParse(xhr.responseText, row); })
    .get(callback);

An optional row conversion function may be specified to map and filter row objects to a more-specific representation; see dsv.parse for details. For example:

function row(d) {
  return {
    year: new Date(+d.Year, 0, 1), // convert "Year" column to Date
    make: d.Make,
    model: d.Model,
    length: +d.Length // convert "Length" column to number
  };
}

The returned request exposes an additional request.row method as an alternative to passing the row conversion function to d3.tsv, allowing you to configure the request before sending it. For example, this:

d3.tsv(url, row, callback);

Is equivalent to this:

d3.tsv(url)
    .row(row)
    .get(callback);

# d3.xml(url[, callback]) <>

Returns a new request to get the XML file at the specified url with the default mime type application/xml. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("application/xml")
    .response(function(xhr) { return xhr.responseXML; });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("application/xml")
    .response(function(xhr) { return xhr.responseXML; })
    .get(callback);

XML parsing relies on xhr.responseXML which is not supported by node-XMLHttpRequest as of version 1.8; thus, this method is supported in browsers but not in Node.

More Repositories

1

d3

Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript
106,311
star
2

d3-shape

Graphical primitives for visualization, such as lines and areas.
JavaScript
2,458
star
3

d3-plugins

[DEPRECATED] A repository for sharing D3.js V3 plugins.
JavaScript
1,808
star
4

d3-force

Force-directed graph layout using velocity Verlet integration.
JavaScript
1,702
star
5

d3-scale

Encodings that map abstract data to visual representation.
JavaScript
1,567
star
6

d3-queue

Evaluate asynchronous tasks with configurable concurrency.
JavaScript
1,411
star
7

d3-hierarchy

2D layout algorithms for visualizing hierarchical data.
JavaScript
1,064
star
8

d3-geo-projection

Extended geographic projections for d3-geo.
JavaScript
1,058
star
9

d3-geo

Geographic projections, spherical shapes and spherical trigonometry.
JavaScript
988
star
10

d3-scale-chromatic

Sequential, diverging and categorical color scales.
JavaScript
787
star
11

d3-sankey

Visualize flow between nodes in a directed acyclic network.
JavaScript
763
star
12

d3-format

Format numbers for human consumption.
JavaScript
611
star
13

d3-delaunay

Compute the Voronoi diagram of a set of two-dimensional points.
JavaScript
606
star
14

d3-ease

Easing functions for smooth animation.
JavaScript
604
star
15

d3-selection

Transform the DOM by selecting elements and joining to data.
JavaScript
547
star
16

d3-zoom

Pan and zoom SVG, HTML or Canvas using mouse or touch input.
JavaScript
495
star
17

d3-contour

Compute contour polygons using marching squares.
JavaScript
487
star
18

d3-interpolate

Interpolate numbers, colors, strings, arrays, objects, whatever!
JavaScript
482
star
19

d3-array

Array manipulation, ordering, searching, summarizing, etc.
JavaScript
452
star
20

d3-dsv

A parser and formatter for delimiter-separated values, such as CSV and TSV.
JavaScript
416
star
21

d3-color

Color spaces! RGB, HSL, Cubehelix, CIELAB, and more.
JavaScript
389
star
22

d3-drag

Drag and drop SVG, HTML or Canvas using mouse or touch input.
JavaScript
328
star
23

d3-time-format

Parse and format times, inspired by strptime and strftime.
JavaScript
324
star
24

d3-voronoi

Compute the Voronoi diagram of a set of two-dimensional points.
JavaScript
250
star
25

d3-hexbin

Group two-dimensional points into hexagonal bins.
JavaScript
231
star
26

d3-time

A calculator for humanity’s peculiar conventions of time.
JavaScript
227
star
27

d3-quadtree

Two-dimensional recursive spatial subdivision.
JavaScript
225
star
28

d3-transition

Animated transitions for D3 selections.
JavaScript
219
star
29

d3-fetch

Convenient parsing for Fetch.
JavaScript
215
star
30

d3-axis

Human-readable reference marks for scales.
JavaScript
204
star
31

d3.github.com

The D3 website.
JavaScript
195
star
32

d3-path

Serialize Canvas path commands to SVG.
JavaScript
192
star
33

d3-timer

An efficient queue for managing thousands of concurrent animations.
JavaScript
159
star
34

d3-brush

Select a one- or two-dimensional region using the mouse or touch.
JavaScript
154
star
35

d3-3.x-api-reference

An archive of the D3 3.x API Reference.
153
star
36

d3-random

Generate random numbers from various distributions.
JavaScript
136
star
37

d3-chord

Visualizations relationships or network flow with a circular layout.
JavaScript
122
star
38

d3-tile

Compute the quadtree tiles to display in a rectangular viewport.
JavaScript
120
star
39

d3-collection

Handy data structures for elements keyed by string.
JavaScript
111
star
40

d3-geo-polygon

Clipping and geometric operations for spherical polygons.
JavaScript
102
star
41

d3-polygon

Geometric operations for two-dimensional polygons.
JavaScript
97
star
42

d3-require

A minimal, promise-based implementation to require asynchronous module definitions.
JavaScript
79
star
43

d3-selection-multi

Multi-value syntax for d3-selection and d3-transition.
JavaScript
75
star
44

d3-dispatch

Register named callbacks and call them with arguments.
JavaScript
75
star
45

versor

a home for Mike Bostock's versor.js
JavaScript
34
star
46

d3-bundler

DEPRECATED; use rollup/rollup.
JavaScript
34
star
47

d3-hsv

The HSV (Hue, Saturation, Value) color space.
JavaScript
26
star
48

d3-logo

D3 brand assets.
23
star
49

d3-cam16

A d3 implementation of the CIECAM16 color appearance model.
JavaScript
22
star
50

d3-hcg

The HCG (Hue, Chroma, Grayness) color space derived from the Munsell color system.
JavaScript
20
star
51

d3-scripts

Common scripts for D3 modules.
JavaScript
15
star
52

d3-hull

DEPRECATED; see d3-polygon’s hull function.
JavaScript
14
star
53

blur-benchmark

temporary benchmark for d3.blur implementations
JavaScript
2
star