XMLHttpRequest


XMLHttpRequest is an object first added to Internet Explorer 5.0 (as the Microsoft.XMLHTTP ActiveX object), and it is core to Ajax. XMLHttpRequest is used to make HTTP queries from a Web page, generally retrieving XML. You can tell that a lot of thought went into the name of the object. The developers of Mozilla (Netscape Navigator and Firefox) obviously recognized the value of this object, and so they added it to those browsers as well. Recently, the World Wide Web Consortium (W3C) started an effort to standardize the functionality of this object as well. In addition, Microsoft has announced that this object would also be available in Internet Explorer 7.

The XMLHttpRequest object can make either synchronous or asynchronous requests. Synchronous requests are like any other normal application call: You make the request, and when the data is returned, your code moves on to the next line. This is simple, but remember that a Web request is being made here-a request that may take some time to complete. If the request is made over a slow link, it could take a lot of time, and your Web page will be not responsive during this time. That is, the user will be staring at a page that doesn't allow him to enter any more data or click buttons until the code has run. Therefore, you should always make asynchronous requests when working with the XMLHttpRequest object. With an asynchronous request, when you make the call to download the data, it happens on a background thread, allowing the code to continue and the main Web page to keep dealing with the user. Obviously, if your code is happening on another thread, some code must process the result when the XMLHttpRequest call is completed. You identify this function when you make the call to download data.

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, methods similar to this are inherently fragile. New browser versions come out, browser agent strings change, or browsers can be set to impersonate other browsers. Instead, you should use code similar to Listing 14-6 to create the XMLHttpRequest object.

Listing 14-5: Creating an XMLHttpRequest object the wrong way

image from book
      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();      } 
image from book

Listing 14-6: Creating an XMLHttpRequest object the correct cross browser way

image from book
      function getReqObj(){          var result=null;          if(window.XMLHttpRequest) {              result = new XMLHttpRequest();          } else {              try {                  result=new ActiveXObject("Msxml2.XMLHTTP");              } catch(e){                  result=null;              }          }          return result;      } 
image from book

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 agnostic request.

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 preceding code can be simplified to:

      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.)

Open table as spreadsheet

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 readyState (see the following) is 3 or 4. With other states, it should always be null.

getResponseHeader

Returns a string containing the value for a requested response header. Note that this value can only be retrieved if the readyState (see the following) is 3 or 4. With other states it should always be null.

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

onreadystatechange

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:

  • q 0 (Uninitialized): The object has been created, but no open method has been called yet.

  • q 1 (Open): Open has been called, but not send.

  • q 2 (Sent): Send has been called, but no data has been received yet.

  • q 3 (Receiving): Data is partially available.

  • q 4 (Loaded): All data and headers have been received. This is the state most code needs before processing the result.

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 formed.

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

image from book
      //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); 
image from book

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.




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net