2.2. Cross-Browser XMLHttpRequest
One of the attributes that have made XMLHttpRequest such a popular transport for AJAX requests is that it is easy to use in a way that is compatible across multiple browsers. The big two browsers, IE and Firefox, provide the same basic API. This consistency makes for a similar development experience. Opera and Safari also support the same basic API, but only in their more recent versions.
Listing 2-1. Cross-Browser XMLHttpRequest Creation
The overall pattern of this code is simple: Create an XMLHttpRequest instance in the most optimal way possible, as shown in line 6. This creation should always succeed on Mozilla-based browsers, such as Firefox, on Opera, and on the upcoming IE 7.
If XMLHttpRequest doesn't exist, catch the exception that is thrown, as shown in line 7. Getting an exception means you're on IE or an old browser. To test for IE, attempt to create an ActiveX version of XMLHttpRequest, which is accomplished by the following:
This approach allows for minimal overhead if the browser supports a native XMLHttpRequest object while fully supporting IE. It also gives us an error if XMLHttpRequest isn't supported at all. This error could be displayed to the user at this point, or you could insert another communication approach, such as hidden IFrames.