One of the things that is in the new version of jPaq is simple AJAX handling. The way that I accomplished it was by using code similar to the following:


/**
 * @license By Chris West - MIT Licensed
 */
(function () {
  /**
   * Array of functions that create XHR objects in different browsers.
   * Will be re-ordered to have the first function in the array be the
   * one that works for the current browser.
   * @type {Array.<Function>}
   * @private
   */
  var xhrMakers = [
    function(){ return new XMLHttpRequest(); },
    function(){ return new ActiveXObject("Msxml2.XMLHTTP"); },
    function(){ return new ActiveXObject("Msxml3.XMLHTTP"); },
    function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }
 ];

  /**
   * Attempts to synchronously pull the content from the specified URL.
   * @param {string} url
   *     The URL of the content to pull from the same domain.
   * @return {string}
   *     The content found at the specified URL.
   */
  requestContentFrom = function (url) {
    var xhr, triesLeft = xhrMakers.length;
    while(0 < triesLeft--) {
      try {
        xhr = xhrMakers[0]();
      }
      catch(e) {
      	// Change order so the correct xhrMaker will always be first.
        xhrMakers.push(xhrMakers.shift());
      }
    }

    if(xhr) {
      xhr.open('GET', url, false); // get page synchronously
      xhr.send();
      return xhr.responseText;
    }
    
    // Throw an error since no xhr could be created.
    throw new Error('AJAX not supported.');
  };
})();

The above code basically provides a function called requestContentFrom(...). This function takes the URL of the content that you are trying to pull and returns the content as a string. Of course, the limitation is that the request must be made to a URL from the same domain. The above code will work in any browser, including IE6+. Feel free to use and beef up the code if you want, but if you are thinking about beefing it up a lot, I would first consider looking for JavaScript libraries that already do this so as not to waste time re-inventing code. šŸ˜‰

Categories: BlogJavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *