【问题标题】:Uncaught TypeError: Cannot read property 'responseXML' of undefined未捕获的类型错误:无法读取未定义的属性“responseXML”
【发布时间】:2018-03-28 09:52:43
【问题描述】:

我正在尝试使用 JavaScript 开发网站,

目标是获取xml文件的数据,并将其转换为vars。

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        initMap(this);
    }
};

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(xml) {
    var xlat, xlon, i, xmlDoc;
    xmlDoc = xml.responseXML;
    xlat = xmlDoc.getElementsByTagName('Lat');
    xlon = xmlDoc.getElementsByTagName('Lon');
    /*
    xlat = xml.responseXML.getElementsByTagName('lat');
    xlon = xml.responseXML.getElementsByTagName('lon');
    */
    for (i = 0; i < xlat.length; i++) {
        var latcode = xlat[i].childNodes[0].nodeValue;
        var loncode = xlon[i].childNodes[0].nodeValue;
        //var myLatLng = "{lat: " + latcode + ", lng: " + loncode +"}";
        //var myLatLng = {lat: latcode, lng: loncode};
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(latcode, loncode),
            map: map,
        });
    }
    [...]
}

但我收到此代码错误:Uncaught TypeError: Cannot read property 'responseXML' of undefined@ -> xmlDoc = xml.responseXML;

我已经尝试将xmlDoc = xml.responseXML; 替换为xmlDoc = this.responseXML;

但我得到 getElementByTagName 的一些错误:Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined

感谢您的帮助! 雅克

编辑:代码来源:Google Doc 是的,现场演示对我有用,我使用的是谷歌浏览器

【问题讨论】:

  • 您的代码对我来说很好用。这里is a live demo 表明它也有效。现场演示对您有用吗?如果是这样,问题出在您没有向我们展示的代码中。否则:您使用的是哪个网络浏览器?
  • 猜猜下一个问题是,哪个浏览器?
  • 代码来源:Google Doc 是的,现场演示适合我,我使用的是谷歌浏览器

标签: javascript xml


【解决方案1】:

对于Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined 错误,XML 文件中的条目之一很可能没有定义您要查找的标记值。扫描 xml 并确保每个条目中都有该标记的值。

我不知道如何处理不完整的文档。

至于Uncaught TypeError: Cannot read property 'responseXML',我在很多似乎都可以正常工作的页面上看到了这一点。到了我现在忽略它的地步;但我希望有人能解释一下,这样我就可以解决根本问题。

【讨论】:

    【解决方案2】:

    这是因为您没有在xlat[i]xlon[i] 给出子节点名称。

    把它改成

    /*var latcode = xlat[i].childNodes[0].nodeValue; var loncode = xlon[i].childNodes[0].nodeValue;*/

    /*
    var latcode = xlat[i].getElementsByTagName("give child node tag name")[0].childNodes[0].nodeValue;
    
     var loncode = xlon[i].getElementsByTagName("give child node tag name")[0].childNodes[0].nodeValue;
    */
    

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2015-01-06
      • 2017-07-26
      • 2019-02-26
      • 2021-12-25
      • 1970-01-01
      • 2017-02-11
      相关资源
      最近更新 更多