views:

1038

answers:

4

I am trying to see what are the gotchas in using XmlHttpWebRequest such that it works for Safari, Firefox and IE?

+1  A: 

Here's somebody who got his hands dirty with that question:

http://www.webmasterworld.com/javascript/3195000.htm

One general way to research these questions is to peek at the source code of a javascript library, like jQuery, since one of the functions of the library is to handle the differences. Here's a snippet of jQuery that deals with XMLHttpRequest. Note the comments about browser differences.

 // Create the request object; Microsoft failed to properly
 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
 var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

 // Open the socket
 // Passing null username, generates a login popup on Opera (#2865)
 if( s.username )
  xhr.open(type, s.url, s.async, s.username, s.password);
 else
  xhr.open(type, s.url, s.async);

 // Need an extra try/catch for cross domain requests in Firefox 3
 try {
Corey Trager
This is fine for a specific loading of HTML into a container but using Microsoft.XMLHTTP progid would be a mistake if you need consistent XML behaviour.
AnthonyWJones
+3  A: 

probably the most obvious difference is how to get an XMLHttpRequest in the first place:

var xhr;
if (window.XMLHttpRequest) {
   xhr = new XMLHttpRequest(); // Mozilla/Webkit/Opera
} else if (window.ActiveXObject) {
   xhr = new ActiveXObject('Msxml2.XMLHTTP'); // IE
} else {
   throw new Error('Ajax likely not supported');
}

that being said, i'd strongly look into an abstraction library such as jQuery. it makes things like ajax ridiculously easy:

$('#container').load('/ajax/resource');
Owen
XMLHttpRequest also applies to IE7. On IE6 the it would be better to use the ProgID MSXML2.XmlHttp.3.0 to ensure a specific implementation returned (in some circumstances a version nuetral ProgID can returen a version 2.0 implementation instead).
AnthonyWJones
There's also the difference between synchronous and asynchronous mode of operation. For some browsers, that implies an extra parameter in the call.
bart
A: 

I know it's a bit of a cop-out answer, but this sort of thing will drive you insane if you use the built-in and inconsistent-across-browsers methods. Pick any javascript library and breathe a sigh of relief.

nickf
+1  A: 

There is a very good article about all major bugs found in XMLHttpRequest implementations and a very light implementation of a XMLHttpRequest wrapper that works around these bugs while exposing exactly the same XMLHttpRequest object.

Sergey Ilinsky