XMLHTTP and XMLHttpRequest
|
|
|
|
| Articles Reviews Ajax | |
| Written by Adi Bach | |
| Saturday, 14 October 2006 | |
|
In the last few months, the use of XMLHTTP and its variants has increased dramatically. The adoption of the technology by Google in their Google Suggest and Google GMail product offerings has been primarily responsible for introducing the development method to the masses. Additionally, an article by
Adaptive Path coining the term
"
The Interfaces
The following are the
methods of the XMLHTTP and XMLHttpRequest interfaces that are relevant and, for the most part,
supported in all browsers:
The open() and send() methods handle the primary functionality of the interface. The open() method sets various parameters of the request, such as the HTTP request method (get or post) and the request URI. The request URI will typically be the relative location of the script on the server to call. You may use a fully qualified URI if you would like, but due to security restrictions, the domain of the URI must match that of the page containing the JavaScript issuing the request. The implication of this is
that if you would like to fetch
data from third-party data sources located on other domains (such as, for
instance, weather data feeds),
you must proxy such requests through a server-side script residing on your
server.
The optional async parameter of the open() method determines the behavior of the send() method. If set to true (or left to its default), the send() method will issue the HTTP request and immediately return. This means that lines of your JavaScript code subsequent to the call to send() will execute regardless of the response to the issued request. Instead, response handling is triggered by the
firing of an event, handled by
an event handler. This feature is the first A in
With the exception of responseText and responseXML, these properties are mainly involved in determining if and when a response has been received. This is necessary because your requests are asynchronous, meaning you cannot rely on the availability of the response at any given line of code based on execution order or time. Rather, asynchronous communication relies on an event-driven model for processing. The readyState property contains a value that indicates the progress of the request. Every time this value changes, a ReadyStateChange event is fired. If defined, the onreadystatechange handler is then called to handle the ReadyStateChange event. Note that for a given request, the readyStateChange event will fire at least four times. In most cases, you will not be interested in any of these events except
for the final one, when the
readyState property changes from 3 (loading) to 4 (complete). However, a
readyState of 4 does not mean
that the request was successful. It indicates only that all operations have
been completed.
You must still check the status property to gain insight to the success of the request. The server could have encountered an error during the processing of the request, for example. If the status property has the integer value of 200 (OK), then the request was successful and any expected response should be avail able in responseXML or responseText. If this seems a bit confusing, that's okay: you'll be diving
into some code next and it
should all come together. Working with the
Interfaces
Because the interface
goes by different names and is instantiated one way for Internet Explorer
(because the interface is an
ActiveX object) and another way in Mozilla, Safari, Konqueror, and Opera,
creating a request object is a
little less straightforward than you might expect. The code shown here is a
very basic method of working
around these browser differences. If you have looked into an implementation of
<script
type="text/javascript"> This code hides
browser differences in instantiation of the XMLHTTP and XMLHttpRequest
interfaces and returns
whichever version is available.
As previously
described, the receipt of the response to an XMLHTTP request is handled with
the firing of events and the
triggering of appropriate event handlers. The next set of code offers the
typical way of handling the
ReadyStateChange event firing and acting on only the event in which you are
interested:
<script
type="text/javascript"> This function is assigned as the onreadystatechange handler and is called when the ReadyStateChange event is fired. It ignores all events where the readyState is not 4 (complete) and the HTTP status code is not 200 (OK). The XML body of complete and successful responses is extracted and passed to another function for processing. Note that after the XML body is retrieved, the request object is set to false. This is to avoid a browser bug in Opera where multiple ReadyStateChange events are sometimes fired when the readyState changes to 4. This could result in acting upon a single response multiple times. Handling the Response
The code in the
previous sections is relatively standard. The complexity in
For example, if you issue a request to the server to check if a username is available, and the server responds with the XML response shown here, then you might wish to display a message to the user indicating that he or she needs to select a different user-name. You may also
wish to offer suggestions based on the alternatives contained in the XML
response: <?xml
version="1.0" encoding="UTF-8"
standalone="yes"?> In this XML response, the server has indicated the
unavailability of a username. Additionally, the server One way you might accomplish conveying this information to the user is by opening a dialog box withJavaScript's alert() function. However, a more user-friendly method might be adding a DIV or UL element in a certain part of the page using DOM manipulations. This offers a less intrusive form of messaging and would allow the user to continue with whatever interaction he is having with your application and tend to the message at his leisure. The following code
offers an example of how the XML tree can be traversed and acted upon appropriately:
<script
type="text/javascript"> This function
processes the XML from the request's responseXML property and adds a UL element
to the DOM.
As you can see, DOM manipulations can be quite complex. The nice thing about this particular response is that you collect username elements regardless of their position in the XML response. Often, you cannot do this directly and you must have an idea of the expected structure of the XML response, or at least where various elements correspond to other elements. This can cause problems if the XML
format is ever amended. Attaching
response handlers at the XML element level, as opposed to the response level, shows some promise in
abstracting the details of the whole XML document, allowing the client-side
script to focus on the local
structure relevant for that particular DOM manipulation.
For example, you might wish to show alternative usernames in a separate DOM element, in which case you would need to differentiate between username elements that do or do not have a parent element of usernamealts. However, you would not need to know how the rest of the XML document is structured and where in the document tree these username elements are located. Implementing this idea would require a mapping between XML element name and handler function. The details of such an implementation are beyond the scope of this chapter, but there are articles available that delve deeper into the subject. Powered by jReviews |
|
| Last Updated ( Friday, 08 June 2007 ) | |
| < Prev | Next > |
|---|







