[thelist] JavaScript variable scope wrong?
Phil Turmel
philip at turmel.org
Wed Aug 3 09:16:10 CDT 2005
Paul Waring wrote:
> I'm having a bit of trouble with what I think is down to variable scope
[snip]
> 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();">
[/snip]
The XMLHttpRequest is asynchronous here, as already noted. That means
your #1 alert is executed before the response arrives and is placed in
the response variable. Ergo, undefined.
The same would be true of the #2 alert, but: It's called from onload(),
so it's delayed enough for the 1st request to complete and fill in the
response variable before the #2 alert is called.
You need to do one of two things:
1) Use XMLHttpRequest in synchronous mode, or
2) Process the response within the processReqChange function.
HTH,
Phil
More information about the thelist
mailing list