In honor of Telemonian Ajax, apparently

By Hal Canary, 2006-11-17 18:22:32 (link)
#computers-code

Read Head Rush Ajax yesterday. If you already know Javascript and the DOM, all there is left to learn about the magic of Ajax is the XMLHttpRequest / Msxml2.XMLHTTP / Microsoft.XMLHTTP functions, which aparently all work identically.

/* ajax-http-request.js */
function newHttpRequest() {
  var request = null;
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
         request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
        }
    }
  }
  return(request);
}

Given that simple library file, you can do this:

/* some-other-javascript-file.js */
var req = newHttpRequest();
if (req == null)
  alert("Error creating request object!");

function dealWithResponse() {
  if (req.readyState == 4) {
    if (req.status == 200)
      doSomethingWith(req.responseText);
    } else {
      throwAnErrorOrSomething();
  }
}
req.open("GET", "someurl", true);
req.onreadystatechange = dealWithResponse;
req.send(null);

And that's all you really need to know to do Ajax.


(back)