Getting Started
The standard way to do Ajax is to use the XMLHttpRequest object, known as XHR by its friends. Use XHR directly, or via one of the helpful Ajax libraries such as Prototype or jQuery. How do we use XHR "by hand"? To start with, we need to get a reference to it:
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}We can then open a connection to a URL:
xhr.open(
"GET",
"my-dynamic-content.jsp?id="
+encodeURI(myId),
true
);Specify a callback function to receive the response:
xhr.onreadystatechange = function(){
processReqChange(req);
}and then send the request:
xhr.send(null);The server may be busy, or the network may be slow. We don't want to sit around doing nothing until the response arrives, and because we've assigned the callback function, we don't have to. That's the five-minute guide for the impatient. For those who like to know the details, we've listed the fuller details of the XHR object below.
| Method Name | Parameters and Descriptions |
|---|---|
| open(method, url, async) | open a connection to a URL method = HTTP verb (GET, POST, etc.) url = url to open, may include querystring async = whether to make asynchronous request |
| onreadystatechange | assign a function object as callback (similar to onclick, onload, etc. in browser event model) |
| setRequestHeader (namevalue) | add a header to the HTTP request |
| send(body) | send the request body = string to be used as request body |
| abort() | stop the XHR from listening for the response |
| readyState | stage in lifecycle of response (only populated after send() is called) |
| httpStatus | The HTTP return code (integer, only populated after response reaches the loaded state) |
| responseText | body of response as a JavaScript string (only set after response reaches the interactive readyState) |
| responseXML | body of the response as a XML document object (only set after response reaches the interactive readyState) |
| getResponseHeader (name) | read a response header by name |
| getAllResponseHeaders() | Get an array of all response header names |
