我有一个奇怪的问题。
我想通过XMLHttpRequest()
加载XML文件并访问它。
我可以在Chrome和Firefox中获得正确的XML文档,但在IE中出错了。
我设置了断点并打印出xhr.responseXML
,发现结果不是IE中的原生文档结构。
铬:
#document
<CONFIG>
....
</CONFIG>
IE:
[object XMLDocument]{activeElement: undefined, alinkColor: "#0000ff", all: undefined, anchors: HTMLCollection {...}, applets: HTMLCollection {...}, ATTRIBUTE_NODE: 2, attributes: null, bgColor: "#ffffff", body: null, CDATA_SECTION_NODE: 4, characterSet: "utf-8", charset: "utf-8", childNodes: NodeList {...}, COMMENT_NODE: 8, compatible: MSCompatibleInfoCollection {...}, compatMode: "CSS1Compat", constructor: XMLDocument {...}, cookie: "", defaultCharset: "big5", defaultView: null, designMode: "inherit" ...}
我怎么解决这个问题?
由于
更新
var xmlData = {};
function loadXMLFile(file, cb) {
var xmlDoc = {};
if (window.ActiveObject) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = true;
xmlDoc.load(file);
xmlData = xmlDoc;
cb();
} else if (document.implementation && document.implementation.createDocument) {
var xhr= new XMLHttpRequest();
xhr.open("GET", file, true);
xhr.responseType = 'document';
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseXML); // reponseXML is different in Chrome and IE
xmlDoc = xhr.responseXML;
xmlData = xmlDoc;
cb();
}
}
};
xhr.send(null);
} else {
console.log('not support javascript');
}
}
function checkExist(name) {
var link = xmlData.getElementById(name).getElementsByTagName('url')[0].innerHTML; // IE appear ERROR here
// SCRIPT5007: Unable to get property 'getElementsByTagName' of undefined or null reference
var ele = document.getElementsByClassName(name);
// do somthing...
}
window.onload = function() {
loadXMLFile(file, function() {
checkExist("ID");
checkExist("NAME");
});
}
答案 0 :(得分:0)
xmlData.getElementById(name)
,这就是问题所在。
getElementById()
方法无法确保访问DOM。换句话说,它可能不适用于特定的浏览器。
最后,我通过jquery而不是纯javascript访问了XML文件。