[JavaScipt] Cross-Browser HTTP GET Request


This post shows how to make HTTP GET request in cross-browser way. The following HTTPGET function demonstrates how to make such AJAX request:

get.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * Cross-browser HTTP GET request
 * @param {string} url The url of HTTP GET request
 * @param {function} callback The callback function if HTTP GET succeeds
 * @param {function} failCallback The callback function if HTTP GET fails
 */
HTTPGET = function(url, callback, failCallback) {
  var xmlhttp;

  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200)
        callback(xmlhttp.responseText, url);
      else
        failCallback(url);
    }
  };

  xmlhttp.open("GET", url, true);
  xmlhttp.send();
};

Usage

usage.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var url = '/demo/path?a=1&b=2';

var callback = function(responseText, url) {
  // write your own handler for success of HTTP GET
  alert('responseText from url ' + url + ':\n'
        + responseText);
};

var failCallback = function(url) {
  // write your own handler for failure of HTTP GET
  alert('fail to get ' + url);
};

HTTPGET(url, callback, failCallback);

Note that you can only make requests in the same domain. To make cross-domain requests, please see reference [1] for more detail. To make cross-browser HTTP POST request, please see reference [2]. To make HTTP POST requests to GAE Python server, see reference [3].


References:

[1]JavaScript Cross-Browser Cross-Domain XMLHttpRequest (XDomainRequest in IE)
[2][JavaScipt] Cross-Browser HTTP POST Request
[3]AJAX Form POST Request to Google App Engine Python
[4]XMLHttpRequest - Web API Interfaces | MDN