For loop generating multiple XML requests in Javascript

siddal

New Member
I need to access a series of XML documents and am trying to do so with a for loop that generates each request dynamically:\[code\]for (i=0;i<routes.length;i++) {routeRequestURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=sf-muni&r=" + routes.name + "&terse";routeRequest.open("GET", routeRequestURL);routeRequest.send();routeResponse = routeRequest.responseXML;route = routeResponse.getElementsByTagName("route")[0];for (var j = 0; j < route.childNodes.length; j++) { if (route.childNodes[j].tagName == "stop") { routes.stops.push(new Stop(route.childNodes[j].getAttribute("tag"), route.childNodes[j].getAttribute("lat"), route.childNodes[j].getAttribute("lon"))); } }}\[/code\]\[code\]routes\[/code\] is an array of \[code\]route\[/code\] objects, which have three variables: \[code\]name\[/code\], \[code\]label\[/code\], and \[code\]stops\[/code\], which is itself an array of \[code\]stop\[/code\] objects.I tried out the code in Chrome's javascript console, and it worked when I ran each line within the outer loop with \[code\]routes[0]\[/code\]. When I tried to run the loop in the console, I got the following error message: \[code\]TypeError: Cannot call method 'getElementsByTagName' of null\[/code\].If running each line of code with \[code\]routes[0]\[/code\] generates no errors, then why is \[code\]routeResponse\[/code\] null during the first iteration of the for loop? Am I missing a closure error somewhere?EDIT: I tried to include a \[code\]readystatechange\[/code\] callback, but, being new to javascript, couldn't quite figure out how to do it. I tried:\[code\]for (i=0;i<routes.length;i++) {routeRequestURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=sf-muni&r=" + routes.name + "&terse";routeRequest.open("GET", routeRequestURL);routeRequest.onreadystatechange = function() { routeResponse = routeRequest.responseXML; route = routeResponse.getElementsByTagName("route")[0]; for (var j = 0; j < route.childNodes.length; j++) { if (route.childNodes[j].tagName == "stop") { routes.stops.push(new Stop(route.childNodes[j].getAttribute("tag"), route.childNodes[j].getAttribute("lat"), route.childNodes[j].getAttribute("lon"))); } } }routeRequest.send();}\[/code\]It didn't work.
 
Back
Top