Andre R.
Andre R.

Reputation: 2799

Explanation of downloadUrl() in Javascript?

I have looked far and wide for an explanation so that i am able to understand the above function. The situation which i have encountered it is in Google Maps API documentation:

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request.responseText, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function doNothing() {}

If someone could shed some light it would be appreciated.

Upvotes: 1

Views: 7095

Answers (2)

mplungjan
mplungjan

Reputation: 177851

function downloadUrl(url, callback) { // pass a URL and a function to call on success
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest; // create an xmlhttprequest, native if possible, activeX for older IE - the construct is a ternary conditional statement
  // set up handling of the state change, we only want the 4th
  request.onreadystatechange = function() { // when the request changes state 
                                            // i.e from sending to having received
    if (request.readyState == 4) { // request done
      request.onreadystatechange = doNothing; // removed this anonymous function on 4th state (done)
      callback(request.responseText, request.status); // call the supplied function with result
    }
  };

  request.open('GET', url, true); // now initialize
  request.send(null); // now execute
}

Update: it is these days (July 2018) more likely to find the XMLHttpRequest than the activeX, so any of the following are recommended:

  • switch the test around,
  • remove the test for activeX,
  • add a try/catch or
  • use Fetch

Upvotes: 2

akonsu
akonsu

Reputation: 29536

this code uses AJAX functionality in the browser to fetch the contents of the URL.

Upvotes: -1

Related Questions