[Wylug-help] AJAX, JS and scoping

Aaron Crane wylug at aaroncrane.co.uk
Fri Aug 17 12:17:10 BST 2007


Gary Stainburn writes:
> <SCRIPT LANGUAGE="JavaScript">

(This isn't related to your problem, but using LANGUAGE="JavaScript"
makes your HTML invalid.  Saying type="text/javascript" instead is the
standards-compliant approach.)

> AjaxRequest itself is obviously working as it should, but how to I
> make the xmlHttp created by it available to the call-back?

Let's start from what should happen when you call your AjaxRequest()
function.  The easiest way to arrange for the code that you give to
AjaxRequest() to be able to access an xmlHttp object is for it to
receive it as a parameter:

  AjaxRequest(url, function (xmlHttp) {
      if (xmlHttp.readyState == 4) {
          // update the document as desired
      }
  });

With that in mind, AjaxRequest() just needs to arrange that the code
called by the onreadystatechange event handler will pass the object
through:

  function AjaxRequest(Url, Fn) {
    var xmlHttp;

    // Create an appropriate xmlHttp object as before:
    try { ... } catch (e) { ... }

    // When it becomes ready, call Fn with the appropriate parameter:
    xmlHttp.onreadystatechange = function () { Fn(xmlHttp) };

    // And send the appropriate request as before:
    xmlHttp.open("GET", Url, true);
    xmlHttp.send(null);
  }

-- 
Aaron Crane



More information about the Wylug-help mailing list