Chapter 20. Scripting HTTP

The Hypertext Transfer Protocol (HTTP) specifies how web browsers request documents from and post form contents to web servers, and how web servers respond to those requests and posts. Web browsers obviously handle a lot of HTTP. Usually, however, HTTP is not under the control of scripts and instead occurs when the user clicks on a link, submits a form, or types a URL. Usually, but not always: it is possible for JavaScript code to script HTTP.

HTTP requests can be initiated when a script sets the location property of a window object or calls the submit() method of a form object. In both cases, the browser loads a new page into the window, overwriting any script that was running there. This kind of trivial HTTP scripting can be useful in a multiframed web page but is not the subject of this chapter. Here we consider how JavaScript code can communicate with a web server without causing the web browser to reload the currently displayed page.

The <img>, <iframe>, and <script> tags have src properties. When a script sets these properties to a URL, an HTTP GET request is initiated to download the content of the URL. A script can therefore pass information to a web server by encoding that information into the query-string portion of the URL of an image and setting the src property of an <img> element. The web server must actually return some image as the result of this request, but it can be invisible: a transparent 1-pixel-by-1-pixel image, for instance.[*

Get JavaScript: The Definitive Guide, 5th 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.