[thelist] JavaScript variable scope wrong?

Paul Waring paul at xk7.net
Wed Aug 3 08:26:10 CDT 2005


I'm having a bit of trouble with what I think is down to variable scope
in JavaScript (though I'm not entirely sure if that's the case, I
haven't written this much client-side scripting for several years). At
the moment I've got code along the lines of the following:

<script language="JavaScript" type="text/javascript">
<!--

var req;
var response;

function loadXMLDoc(url)
{
	req = new XMLHttpRequest();
	req.onreadystatechange = processReqChange;
	req.open("GET", url, true);
	req.send(null);
}

function processReqChange()
{
	if ( req.readyState == 4 )
	{
		if ( req.status == 200 )
		{
			response = req.responseXML.documentElement;
		}
	}
}

loadXMLDoc('urlToXML');
alert("1. " + response); // prints "1. undefined"

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

-->
</script>
</head>
<body onLoad="init();">

I've snipped the code to do things like use ActiveXObject for IE (I'm
only testing in Mozilla at the moment and the browser detection code
works anyway, don't see much point in posting huge chunks of it) and the
error checking for the processReqChange() function.

Anyway, the problem is the two loadXMLDoc() calls (both are reading in
the same URL). At the moment, the first one sets response to undefined,
and the second one sets it to [object element] (which is correct, I've
checked what's actually in that object and it's what I want). Here's
where the weird behaviour that I don't understand starts though:

1. If I comment out the first loadXMLDoc call, the response variable in the
main <script> section *and* in the init() function is set to undefined,
which is obviously a bit useless as I can't get at the XML I've tried to
read in.

2. If I comment out the second loadXMLDoc call but leave the first one
running, then within the init() function the response variable is set as
I want it to be, and all is well. However, if I then get rid of the
alert("1. " + response); code (because I don't want stuff like that on
pages that non-developers are going to see) then the response within the
init() function is undefined (this also happens if I comment out the
alert("1.") part and leave both loadXMLDoc calls in).

The best guess I can make is that either the response variable isn't
being set *or* the script is somehow waiting for the loadXMLDoc function
to finish before calling the alert("1.") code.

Sorry if this seems a bit of a convoluted question, but I have very
little idea as to why the script is playing up like this. The JavaScript
console in Mozilla doesn't throw up any errors, except if I try to
access the response variable anywhere when it is still undefined (e.g.
response.getElementsByTagName()).

Thanks in advance for any help/pointers,

Paul

-- 
Rogue Tory
http://www.roguetory.org.uk


More information about the thelist mailing list