Search code examples
javascriptajaxxmlhttprequestactivexobject

Anything wrong with this short XMLHttpRequest declaration?


In all the AJAX libraries I've checked out, XMLHttpRequest involves a lengthy declaration with tests or try/catch statements.

I need to retrieve XML via a SOAP GET request, and I tested the following declaration successfully in IE7+, Firefox and Chrome:

var xhr=new XMLHttpRequest()||new ActiveXObject("Microsoft.XMLHTTP");

What am I missing here? Did I overlook some edge cases where my declaration is going to break?

Edit

So the second part of the declaration never runs. Does it means that for IE7+/Firefox/Chrome I just need:

var xhr=new XMLHttpRequest();

Solution

  • new has precendence, so you're executing new XMLHttpRequest() and check the return value. However, in case XMLHttpRequest is not defined, this execution already throws an error. Rather, you want to check whether XMLHttpRequest is defined before applying new, e.g.:

    var xhr = typeof XMLHttpRequest === "undefined"
                ? new ActiveXObject("Microsoft.XMLHTTP")
                : new XMLHttpRequest; // you can leave out the parens with no arguments