XMLHttpRequest
is an object first added to Internet Explorer 5.0 (as the
Microsoft.XMLHTTP
ActiveX object), and it is
The
XMLHttpRequest
object can make either synchronous or asynchronous requests. Synchronous
Creating an
XMLHttpRequest
object is slightly more complex than it should be. It is implemented as one of two ActiveX objects in Internet Explorer (depending on the version), but it is a natively available object in Firefox, Opera, and Safari. You must create a method to create this object. Many people write a routine that uses the User Agent to decide how to create it (see Listing 14-5). However,
Listing 14-5: Creating an XMLHttpRequest object the wrong way
|
|
var browser=navigator.userAgent.toLowerCase(); var majorVersion = parseInt(navigator.appVersion); var minorVersion = parseFloat(navigator.appVersion); var isIE = ((browser.indexOf("msie") != -1) && (browser.indexOf("opera") == -1)); var isMozilla == (browser.indexOf('mozilla')!= var req; if(isIE) { if(majorVersion = 7) { req = new XMLHttpRequest(); } else if (majorVersion > 6) { req = new ActiveXObject("Microsoft.XMLHTTP"); } else if (majorVersion > 4) { req = new ActiveXObject("Msxml2.XMLHTTP"); } } else { req = new XMLHttpRequest(); }
|
|
Listing 14-6: Creating an XMLHttpRequest object the correct cross browser way
|
|
function getReqObj(){ var result=null; if(window.XMLHttpRequest) { result = new XMLHttpRequest(); } else { try { result=new ActiveXObject("Msxml2.XMLHTTP"); } catch(e){ result=null; } } return result; }
|
|
Because exceptions require some time to process, it is best to attempt to avoid them if possible. Therefore, you make a check to
window.XMLHttpRequest
. If the object is available (the code is running within Firefox, Opera, Safari, or Internet Explorer 7), the remainder of the code and any possible exceptions are avoided. Next, the code attempts to create the
Msxml2.XMLHTTP
ActiveX object. This is the current version of the object, and the name is the version
The good news is that with Internet Explorer 7.0, the
XMLHttpRequest
object will become a native object. This means that, at some point (when you want to forget about supporting Internet Explorer 5-6), the
var req = new XMLHttpRequest();
After you have created an instance of the XMLHttpRequest object, review the methods and properties it makes available. (See the following table.)
|
Method |
Description |
|---|---|
|
abort |
Cancels the current request. Because most of your requests should be asynchronous, this method is a useful method for canceling long-running requests. |
|
getAllResponseHeaders |
Returns a string containing all response headers for the request. Each name:value pair is separated by CR/LF. Note that this value can only be retrieved if the
|
|
getResponseHeader |
Returns a string containing the value for a
|
|
open |
Opens a new request, preparing for a call. If an existing request is in progress, this is reset. A number of overridden versions of this method are available (see text). |
|
send |
Sends the request to the URI assigned in the call to open and prepares the object to receive the returned data. The send method takes a single parameter, which can be either a block of text or XML document. |
|
setRequestHeader |
Adds a custom header to the request. This can be useful for authentication (providing a magic token in the headers of the request), or to modify the behavior of the called service (the header could provide additional parameters for the call or change the identification of the User Agent). |
|
addEventListener |
Available only with the Mozilla version of the object. Associates an event listener to the object. This can be used to override the behavior of the object or to limit other code from accessing the results of the call. |
|
dispatchEvent |
Available only with the Mozilla version of the object. Triggers an event that other code may respond to. This can be useful to bubble the events normally if the addEventListener captures all returned events. |
|
openRequest |
Available only with the Mozilla version of the object. |
|
overrideMimeType |
Available only with the Mozilla version of the object. |
|
removeEventListener |
Available only with the Mozilla version of the object. Disconnects an event listener connected via addEventListener . |
In addition to the methods listed in the preceding table, some of the implementation provides a number of properties that can assist you when you are working with the XMLHttpRequest object. The following table shows those properties:
Open table as spreadsheet
|
Property |
Type |
Description |
|---|---|---|
|
|
function/event listener |
OnReadyStateChange provides a hook for you to add a routine to provide handling for asynchronous requests. The method associated with the event is called when the asynchronous method completes. |
|
readyState |
enumeration |
A read-only value describing the current status of the request. This must be one of the following values:
|
|
responseBody |
byte[] |
Only available when using the Internet Explorer version of the object. This property contains the raw content of the response as an array of bytes. It can be helpful when you are using the XMLHttpRequest object to return non-text data such as a media file. |
|
responseText |
string |
Returns the body of the response as a string. If the readyState is 3, this may not be the complete returned content. |
|
responseXML |
XML Document |
Returns the body of the response as an XML document. Note that this property is really only useful if you are returning XML from the server. If the
readyState
is 3, the entire document is not yet available, and the document may not be well
|
|
status |
int (short) |
The returned HTTP status code for the request. For example, 200 means a successful request. Note that this is only available if the readyState is 3 or 4. |
|
statusText |
string |
The returned HTTP status code text for the request. For example, if the status is 500, the statusText property can provide more information on the reason for the error. Note that this is only available if the readyState is 3 or 4. |
As you can see from the preceding table, the actual target of the request is set using the open method. The simplest version of this method takes two parameters: method and URI. Method is the HTTP method (typically GET or POST) that the request will use. URI represents the target of the call.
var req = GetReqObj(); req.open("GET", "someendpoint.php");
In addition to these two parameters, three other parameters are optional:
q async -A Boolean value that determines whether the request should be made asynchronously or synchronously. Generally, you want to make your XMLHttpRequest calls asynchronously. Synchronous calls prevent the user from interacting with the rest of your Web page, thereby reducing the overall value of using Ajax. Listing 14-7 shows the basic process when making asynchronous requests.
q user -A string identifying the credentials that should be used when processing the request.
q password -A string identifying the password for the user passed in the previous parameter.
Listing 14-7: Pseudocode for XMLHttpRequest calls
|
|
//Create the XMLHttpRequest object var req = getReqObj(); //set the URL and method and configure call as asynchronous req.open("GET", "http://someendpoint", true); //set the function that will respond when the call is complete req.onreadystatechange = MyFunc; req.send(data);
|
|
The onreadystatechange property identifies a function that is called whenever the status of the call changes. Therefore, you must determine the overall status of the request in this function. That is, you should determine if the status is 3 (loading) or 4 (complete) before processing any data. Statuses 1 and 2 may be useful to report to your users, however.