Cross Domain AJAX Requests with jQuery and XDomainRequest

So, you're writing a page that consumes JSON from another domain using (what else?) jQuery. But wait, no browser on the face of the earth should be allowing you to do that, right? Well, maybe. Recently, I had to do just that. After figuring out the details to get Apache to send the appropriate headers (Access-Control-Allow-Origin "*"), I trudged along, completing the code in Chrome. I finalized the product in Firefox. Then, I almost punched the computer screen when I started working in IE.

First, IE does not respect jQuery's XMLHTTPRequest wrappers, and in stead, prefers it's semi-proprietary mix of voodoo and pseudo-logic: XDomainRequest. Fine. I'll do it their way. Oh wait, Chrome and Firefox don't implement XDomainRequest the same way. Damnit, I thought these days were over.

So, here's the final code that I came up with:

    function successFunction(data) {
      if (jQuery.browser.msie) {
        data = jQuery.parseJSON(data);
      }
      /* Yes, if you're using IE, you get text back, not a JSON object */
    }

    if (jQuery.browser.msie) {
      if (window.XDomainRequest) {
        var xdr = new XDomainRequest();
        if (xdr) {
          xdr.onload = function() { successFunction(xdr.responseText); }
          xdr.onerror = function() { /* error handling here */ }
          xdr.open('GET', queryURL);
          xdr.send();
        }
      }
    }
    else {
      jQuery.ajax({
        type: 'GET',
        url: queryURL, 
        dataType: "json",
        success: function(data, textStatus, jqXHR) { successFunction(data); },
        error: function(jqXHR, textStatus, errorThrown) { /* error handling here */ }
      });
    }
javascript
jQuery