Thursday, November 17th, 2005

Issues when working with Ajax

Category: Articles, Editorial

Mercury Tide has written a mini-paper on Issues when working with Ajax.

They cover basic items to do with working with XMLHttpRequest, focusing on cross-browser issues.

Getting the XMLHttpRequest Object

They start with how to get the object itself:

function getNewXMLHttpRequest() {
  var obj;
    try {
      // For Internet Explorer.
      obj = new ActiveXObject('Microsoft.XMLHTTP');
    }
    catch(e) {
      try {
        // Gecko-based browsers, Safari, and Opera.
        obj = new XMLHttpRequest();
      }
      catch (e) {
        // Browser supports Javascript but not XMLHttpRequest.
        obj = false;
      }
    }
    return obj;
}

I actually prefer the clean way that Prototype does this:

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false;
  }
}

Interestingly the XMLHttpRequest call is last. If IE7 implements a native XMLHttpRequest, and they allow the ActiveXObject for backwards compatibility, maybe checking for window.XMLHttpRequest first is best?

Working with Headers

Then, they talk about setting request headers, and issues within the browsers, concluding that:

If you want to be sure of a server receiving the referrer, it’s recommended you use a custom header:

request.setRequestHeader('X-Referer', document.location);

referrers-in-browsers.png

Using the server response

In some cases you may want to receive an HTML document fragment to include in the web page, in which case you’ll a string serialisation of the document fragment to insert. As often with Javascript, this varies by browser: Gecko-based browsers, Safari, and Opera use the XMLSerializer object while Internet Explorer has an xml property.

Posted by Dion Almaer at 12:12 am
Comment here

+++--
3 rating from 5 votes

Comments Here »

Comments feed

Leave a comment

You must be logged in to post a comment.