Chapter 13. Networking

This chapter describes four techniques for client-side JavaScript networking. The first, XMLHttpRequest, is well-known and widely-used in the “Ajax” application architecture. This API is by far the most important of the four, and the bulk of the chapter is devoted to it. The chapter also demonstrates the JSONP technique for Ajax-style networking with the <script> tag, as well as “server push” or “Comet” style networking with the new EventSource API, and bidirectional socket-style networking with WebSockets.

Using XMLHttpRequest

Browsers define their HTTP API on an XMLHttpRequest class. Each instance of this class represents a single HTTP request/response pair, and the properties and methods of the object allow you to specify request details and extract response data. XMLHttpRequest is often abbreviated as XHR, and this chapter uses the term XHR2 to refer to cutting-edge features introduced by drafts of version 2 of the XHR specification. Note that the XMLHttpRequest API has nothing to do with XML: the name is a historical accident that we’re simply stuck with.

The first step in using the XHR API, of course, is to instantiate an XMLHttpRequest object:

var request = new XMLHttpRequest();

You can also reuse an existing XMLHttpRequest object, but note that doing so will abort any request pending through that object.

Any HTTP request consists of four parts:

  • the HTTP request method or “verb”

  • the URL being requested

  • an optional set of request headers, ...

Get JavaScript Pocket Reference, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.