XMLHttpRequest makes sending HTTP requests very easy. You simply create an instance of the object, open a URL, and send the request. The HTTP status of the result, as well as the result's contents, are available in the request object when the transation is completed.
Synchronous and asynchronous requests
XMLHttpRequest supports both synchronous and asynchronous communications.
Example: Synchronous request
This example demonstrates how to make a simple synchronous request.
XMLHttpRequestsbecause they block the application's user interface.
var req = new XMLHttpRequest(); req.open('GET', 'http://www.mozilla.org/', false); req.send(null); if(req.status == 200) dump(req.responseText);
Line 1 instantiates the
XMLHttpRequest object. Line 2 then opens a new request, specifying that a
GET request will be used to fetch the Mozilla.org home page, and that the operation should not be asynchronous.
Line 3 sends the request. The
null parameter indicates that no body content is needed for the
Line 4 checks the status code after the transaction is completed. If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.
Example: Non-HTTP synchronous request
Despite its name,
XMLHttpRequest can be used for non-HTTP requests. This example shows how to use it to fetch a file from the local file system.
var req = new XMLHttpRequest(); req.open('GET', 'file:///home/user/file.json', false); req.send(null); if(req.status == 0) dump(req.responseText);
The key thing to note here is that the result status is being compared to 0 for success instead of 200. This is because the
ftp schemes do not use HTTP result codes.