2009
Aug
07

What is the XMLHttpRequest object?

  • Creating an XMLHttpRequest object.
  • Specifying and submitting your HTTP request to a web server.
  • Synchronously or asynchronously retrieving the server's response.
Propertie Name Description
onreadystatechange An event handler for an event that fires at every state change.
readyState The readyState property defines the current state of the XMLHttpRequest object.

State Description
0: The request is not initialized.
1: The request has been set up.
2: The request has been sent.
3: The request is in process.
4: The request is completed.

readyState = 0 after you have created the XMLHttpRequest object, but before you have called the open() method.
readyState = 1 after you have called the open() method, but before you have called send().
readyState = 2 after you have called the send() method.
readyState = 3 after browser has established a communication with the server, but before the server has completed the response.
readyState = 4 after the request has been completed, and the response data have been completely received from the server.

responseText Returns the response as a string.
responseXML Returns the response as XML, which can be examined and parsed using W3C DOM node tree methods and properties. This property returns an XML document object, when the Content-Type header specifies the MIME(media) type as text/xml, application/xml, or ends in +xml. If the Content-Type header does not contain one of these media types, the responseXML value is null.
status Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").
statusText Returns the status as a string (e.g. "Not Found" or "OK").
Method Name Description
abort() Cancel the current request.
getAllResponseHeaders() The getAllResponseHeaders() method returns all the response headers as a single string with each header on a separate line. The method returns null if readyState value is not 3 or 4.
getResponseHeader(DOMString header) Returns the value of the specified HTTP header. Call getResponseHeader() only when the readyState value is 3 or 4 (in other words, after the response headers are available); otherwise, the method returns an empty string.
open(DOMString method, DOMString url, boolean async, DOMString username, DOMString password) Specify the method, url, and other optional attributes of a request.
The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible.
The async parameter specifies whether the request should be handled asynchronously or not. "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing.
send() After preparing a request by calling the open() method, you send the request to the server. You may call send() only when the readyState value is 1, otherwise the XMLHttpRequest object raises an exception. The request gets sent to the server using the parameters supplied to the open() method. The send() method returns immediately when the async parameter is true, letting other client script processing continue. The XMLHttpRequest object sets the readyState value to 2 (Sent) after the send() method has been called. When the server responds, before receiving the message body, if any, the XMLHttpRequest object sets readState to 3 (Receiving). When the request has completed loading it sets readyState to 4 (Loaded). For a request of type HEAD, it sets the readyState value to 4 immediately after setting it to 3.
The send() method takes an optional parameter that may contain data of varying types. Typically, you use this to send data to the server using the POST method. You can explicitly invoke the send() method with null, which is the same as invoking it with no argument. For most other data types, set the Content-Type header using the setReuqestHeader() method before invoking the send() method. If the data parameter in the send(data) method is of type DOMString, encode the data as UTF-8. If data is of type Document, serialize the data using the encoding specified by data.xmlEncoding, if supported or UTF-8 otherwise.
setRequestHeader(DOMString header, DOMString value) The setRequestHeader() method sets request headers. You may call this method after calling the open() method when the readyState value is 1; otherwise you will get an exception.

Create an XMLHttpRequest Object

Example
  1. function createHttpRequest() {
  2. var httpRequest = null;
  3. if (window.ActiveXObject) { // For IE6 and below
  4. httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
  5. } else { // For IE7 and Modern Browsers
  6. httpRequest = new XMLHttpRequest();
  7. }
  8. return httpRequest;
  9. }

Submit a Request

Example
  1. XMLHttpRequest.open("GET", url, true);

If you pass false as the third argument to open(), the send() method is synchronous: it blocks and does not return until the server's response has arrived. Asynchronous responses are generally preferred.

HTTP GET

Example
  1. var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  2. xmlHttpRequest.onreadystatechange = function() {
  3. }
  4. xmlHttpRequest.open("GET", "query.php?username=vivian", false);
  5. xmlHttpRequest.send(null);

HTTP POST

Example
  1. var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  2. xmlHttpRequest.onreadystatechange = function() {
  3. }
  4. xmlHttpRequest.open("POST", "query.php", false);
  5. xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  6. xmlHttpRequest.send("username=vivian");

With POST requests, data is passed to the server in the body of the request, rather than encoding it into the URL itself. Since request parameters are encoded into the URL of a GET request, the GET method is suitable only when the request has no side effects on the server -- that is, when repeated GET requests for the same URL with the same parameters can be expected to return the same result. When there are side effects to a request (such as when the server stores some of the parameters in a database), a POST request should be used instead.

Escape the Data

Example
  1. var HTTPUTILITY = {
  2. encodeFormData: function(data) {
  3. if (!data) {
  4. return;
  5. }
  6. var pairs = [];
  7. var regexp = /%20/g; // A regular expression to match an encoded space.
  8. for (var name in data) {
  9. // Create a name/value pair, but encode name and value first. The global function encodeURIComponent does almost what we want,
  10. // but it encodes spaces as %20 instead of as "+". We have to fix that with String.replace().
  11. var value = data[name].toString();
  12. var pair = encodeURIComponent(name).replace(regexp, "+") + "=" + encodeURIComponent(value).replace(regexp, "+");
  13. pairs.push(pair);
  14. }
  15. return pairs.join("&"); // Concatenate all the name/value pairs, separating them with &.
  16. }
  17. };

The POST method uses the AJAX.encodeFormData() function to convert the properties of an object to a string form that can be used as the body of a POST request. This string is then passed to the XMLHttpRequest.send() method and becomes the body of the request. (The string returned by AJAX.encodeFormData() can also be appended to a GET URL; just use a quest-mark character to separate the URL from the data.)

Retrieve the Response

Example
  1. var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  2. xmlHttpRequest.onreadystatechange = function() {
  3. if (xmlHttpRequest.readyState != 4) {
  4. // Start to progress
  5. } else { // The server's response is complete.
  6. if (xmlHttpRequest.status == 0 || xmlHttpRequest.status == 200) {
  7. callback(xmlHttpRequest.responseText);
  8. } else {
  9. // Error
  10. }
  11. }
  12. }
  13. xmlHttpRequest.open("POST", "query.php", false);
  14. xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  15. xmlHttpRequest.send("username=vivian");

Notes on readyState 3

Data is being received from the server.readyState 3 differs somewhat in Firefox and Internet Explorer. Firefox invokes the onreadystatechange handler multiple times in readyState 3, to provide download progress feedback. A script might use these multiple invocations to display a progress indicator to the user. Internet Explorer, on the other hand, interprets the event handler name strictly, and invokes it only when the readyState value actualy changes. This means that it is invoked only once for readyState 3, no matter how large downloaded document is.

Time Out a Request

Example
  1. var timer = null;
  2. var timeout = 1000;
  3. var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  4. if (timeout) {
  5. if (timer) {
  6. clearTimeout(timer);
  7. }
  8. timer = setTimeout(function(){
  9. xmlHttpRequest.abort();
  10. }, timeout);
  11. }
  12. xmlHttpRequest.onreadystatechange = function() {
  13. if (xmlHttpRequest.readyState != 4) {
  14. // Start to progress
  15. } else { // The server's response is complete.
  16. if (timer) {
  17. clearTimeout(timer);
  18. }
  19. if (xmlHttpRequest.status == 0 || xmlHttpRequest.status == 200) {
  20. callback(xmlHttpRequest.responseText);
  21. } else {
  22. // Error
  23. }
  24. }
  25. }
  26. xmlHttpRequest.open("POST", "query.php", false);
  27. xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  28. xmlHttpRequest.send("username=vivian");

Prevent Caching for Internet Explorer

By appending the julian day number to the end of the URL(?timestamp=123412341234), we effectively make each call unique and that means Internet Explorer will not cache the Ajax call as it is wont to do.

View Demo

Related Posts


回應 (Leave a comment)