JavaScript获取XML数据报错:Uncaught TypeError: responseXML未定义
解决"Uncaught TypeError: Cannot read property 'responseXML' of undefined"错误
这个错误的核心原因是你在initMap函数中尝试访问某个未定义对象的responseXML属性。结合你给出的代码片段来看,大概率是initMap函数的实现不完整,或者没有正确使用传入的XMLHttpRequest实例参数。
修正后的完整代码
首先,我们补全并修正你的代码,确保能正确获取XML数据并转换为变量:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { // 确认请求已完成且成功 if (this.readyState === 4 && this.status === 200) { initMap(this); // 这里的this指向当前XMLHttpRequest实例 } }; xhttp.open("GET", "https://applications002.brest-metropole.fr/WIPOD01/Transport/REST/getGeolocatedVehiclesPosition?format=xml&route_id=1&trip_headsign=Fort%20Montbarey", true); xhttp.send(); function initMap(xhr) { // 先做空值检查,避免意外报错 if (!xhr || !xhr.responseXML) { console.error("无法获取有效的XML响应"); return; } // 获取XML文档对象 const xmlDoc = xhr.responseXML; // 示例:提取车辆坐标并转换为变量 const vehicles = xmlDoc.getElementsByTagName("vehicle"); for (let i = 0; i < vehicles.length; i++) { const vehicleLat = vehicles[i].getAttribute("latitude"); const vehicleLon = vehicles[i].getAttribute("longitude"); const vehicleId = vehicles[i].getAttribute("vehicle_id"); // 这里就可以把这些变量用于后续逻辑,比如地图渲染 console.log(`车辆 ${vehicleId} 的坐标:${vehicleLat}, ${vehicleLon}`); } }
关键说明
- 正确使用传入的参数:你调用
initMap(this)时,this就是当前的XMLHttpRequest实例,所以在initMap里要通过传入的xhr参数来访问responseXML,而不是去引用其他未定义的变量。 - 添加空值校验:增加
!xhr || !xhr.responseXML的检查,能在请求异常时给出友好提示,避免直接抛出错误。 - XML数据提取示例:演示了如何从XML中提取属性值并转换成可使用的变量,你可以根据实际XML结构调整提取逻辑。
现代替代方案:使用Fetch API
如果你愿意使用更现代的写法,Fetch API比XMLHttpRequest更简洁易读:
fetch("https://applications002.brest-metropole.fr/WIPOD01/Transport/REST/getGeolocatedVehiclesPosition?format=xml&route_id=1&trip_headsign=Fort%20Montbarey") .then(response => { if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } return response.text(); }) .then(xmlText => { // 将XML文本解析为DOM对象 const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlText, "application/xml"); // 后续数据提取逻辑和上面一致 const vehicles = xmlDoc.getElementsByTagName("vehicle"); vehicles.forEach((vehicle, index) => { const lat = vehicle.getAttribute("latitude"); const lon = vehicle.getAttribute("longitude"); console.log(`车辆 ${index+1} 坐标:${lat}, ${lon}`); }); }) .catch(error => console.error("处理请求时出错:", error));
内容的提问来源于stack exchange,提问作者Jacques
相关产品推荐
相关产品推荐

