[英]Javascript error when reading large XML file
我正在使用以下代码读取大型sitemap.xml文件:
<div id="urls"></div>
<script type="text/javascript" language="javascript">
var xmlhttp;
if(window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
loc = xmlhttp.responseXML.documentElement.getElementsByTagName("loc");
for(i=0;i<loc.length;i++) {
document.getElementById("urls").appendChild(document.createTextNode( loc[i].firstChild.nodeValue ));
document.getElementById("urls").appendChild(document.createElement("br"));
}
document.getElementById("urls").innerHTML = table;
}
}
xmlhttp.open("GET", "sitemap.xml", true);
xmlhttp.send(null);
</script>
读取多于1000行的XML文件时,将显示以下详细信息错误:
未捕获的TypeError:无法读取null(索引)的属性'documentElement':xmlhttp.onreadystatechange
关于如何解决这个问题的任何想法? 尝试了一些我在网上找到的东西,但无法正常解决。
非常感谢您的帮助。
您必须检查responseXML
是否为null
。 如果服务器返回的XML文件存在解析错误,则会发生这种情况。
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
var locs, i, urls = document.getElementById("urls");
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if (this.responseXML) {
locs = this.responseXML.documentElement.getElementsByTagName("loc");
for (i = 0; i < locs.length; i++) {
urls.appendChild(document.createTextNode(locs[i].firstChild.nodeValue));
urls.appendChild(document.createElement("br"));
}
// What is that line? I've taken it from your code, but it can't be right.
urls.innerHTML = table;
} else {
// responseXML is null if the response has XML parsing errors
alert("The server did not send a proper sitemap file.");
}
}
};
xmlhttp.open("GET", "sitemap.xml");
xmlhttp.send();
另外,如上所示,您绝对不应使用同步请求。 具有事件处理回调函数(如onreadystatechange
)的全部目的是能够发出异步请求。
MDN上还有一个关于此的红色警告: https : //developer.mozilla.org/en/docs/Web/API/XMLHttpRequest#onreadystatechange
经验教训:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.