[thelist] JavaScript variable scope wrong?

marcus m-lists at bristav.se
Wed Aug 3 09:40:27 CDT 2005


Your problem is that when you do the first
  loadXMLDoc('urlToXML');
  alert("1. " + response); // prints "1. undefined"

  function init()
  {
  	loadXMLDoc('urlToXML');
  	alert("2. " + response); // prints "2. [object element]
  }

The first loadXMLDoc and alert("1...") is run when the page is loading 
(ie before init() is called). Since you are using the async variant of 
xmlhttprequest loadXMLDoc returns immediately and then the first alert 
is called. When this happens you haven't gotten to the part where you 
assign the response variable. This will, most probably, occur when the 
alert is visible. So when init is called and loadXMLDoc() is called a 
second time. The difference is that in this case you have already 
assigned the response variable to the correct value from the first call 
and it is this you see in the second alert.

If you do the following I guess you will get the behaviour you expect:

function loadXMLDoc(url, callback) {
   req = new XMLHttpRequest();
   req.onreadystatechange = function() {
     if ( req.readyState == 4 ) {
       if ( req.status == 200 ) {
         callback(req.responseXML.documentElement);
       }
     }
   }
   req.open("GET", url, true);
   req.send(null);
}

Then you use it like this:

function init() {
   loadXMLDoc('urlToXml', function(response) {
     alert("1." + response);
   });
}

Or like this:

function handleResponse(response) {
   alert("2." + response);
}

function init() {
   loadXMLDoc('urlToXml', handleResponse);
}

init() and init2() does the same thing except that the callback is an 
anonymous function in the first case and an explicit function reference 
in the second case.

Hope it helps.

/Marcus



More information about the thelist mailing list