0
生成多個XML請求我需要訪問一系列的XML文檔,我試圖用一個for循環,動態地生成每個請求這樣做:For循環Javascript中
for (i=0;i<routes.length;i++) {
routeRequestURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=sf-muni&r=" + routes[i].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[i].stops.push(new Stop(route.childNodes[j].getAttribute("tag"), route.childNodes[j].getAttribute("lat"), route.childNodes[j].getAttribute("lon")));
}
}
}
routes
是route
對象的數組,它有三個變量:name
,label
和stops
,它本身是一個stop
對象的數組。
我試用了Chrome的javascript控制檯中的代碼,當我在routes[0]
的外部循環中運行每行時,它工作。當我試圖在控制檯中運行循環時,出現以下錯誤消息:TypeError: Cannot call method 'getElementsByTagName' of null
。
如果運行routes[0]
的每行代碼都不會生成錯誤,那麼爲什麼在for循環的第一次迭代期間爲空?我是否錯過了某處的關閉錯誤?
編輯:我試圖包括一個readystatechange
回調,但是,對JavaScript來說是新手,無法完全弄清楚如何去做。我嘗試過:
for (i=0;i<routes.length;i++) {
routeRequestURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=sf-muni&r=" + routes[i].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[i].stops.push(new Stop(route.childNodes[j].getAttribute("tag"), route.childNodes[j].getAttribute("lat"), route.childNodes[j].getAttribute("lon")));
}
}
}
routeRequest.send();
}
它沒有工作。
你錯過了'readystatechange'回調,因爲該請求是異步的。 – bfavaretto
我很新的JavaScript ...我將如何包括該回調? – giaour