1

[JavaScipt] Cross-Browser HTTP GET Request

 2 years ago
source link: https://siongui.github.io/2012/10/05/javascript-http-get-request/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[JavaScipt] Cross-Browser HTTP GET Request

Updated: March 02, 2015

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
/**
 * 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
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:

[4]XMLHttpRequest - Web API Interfaces | MDN


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK