1

我正在尝试编写一个 Internet Explorer 8 解决方案,用于通过“文件”协议加载 XML,因为我正在构建的站点旨在作为包直接发送给用户。我在尝试使用 XMLHttpRequest 处理此问题时所经历的一切似乎都支持我在网上阅读的内容:IE8 的 XMLHttpRequest 实现不喜欢该协议,因此我必须使用 ActiveXObject 来处理加载。

我已经尝试了各种人的建议,最后有似乎成功获取文件的代码,因为 responseText 字段填充了文件的内容。但是,应该保存 XML 的 responseXML.xml 字段(或它的文本表示,我读过的文档都不是很清楚)始终是一个空字符串。如何配置 ActiveXObject 以正确加载 XML?

作为奖励,有人还可以解释我应该如何在加载成功后使用加载的 XML 吗?我还没有找到任何解释这一点的文件。

这是我的 JavaScript:

function isIE() {
    return navigator.userAgent.lastIndexOf('Trident') > 0;
}

// This block ensures that the XML request occurs in the same domain.
var path = document.location.href;
path = path.substr(0, path.lastIndexOf('/') + 1);

if (isIE() && location.protocol == 'file:') {
    var xmlRequest = new ActiveXObject('MSXML2.XMLHTTP');
    xmlRequest.open('GET', path + 'xml/shared.xml', false);
    xmlRequest.onreadystatechange = useXML;
    xmlRequest.send();

    function useXML() {
        if (xmlRequest && xmlRequest.readyState && xmlRequest.readyState == 4) {
            alert(xmlRequest.responseText);    // displays the file
            alert(xmlRequest.responseXML.xml); // displays nothing
        }
    }
}

这是我的 XML 文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<shared>
    <page_title>
        Test Page Title
    </page_title>
</shared>

我使用 w3schools XML 验证器来检查该文件是否存在某种格式错误。它不是。

4

1 回答 1

2

这是因为本地文件不作为 text/xml 提供(服务器会这样做),所以 IE 不会解析它。

Microsoft.XMLDOM您可以使用对象手动解析它

function useXML() {
        if (xmlRequest && xmlRequest.readyState && xmlRequest.readyState == 4) {
            alert(xmlRequest.responseText);    // displays the file
            xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async="false";
            xmlDoc.loadXML(xmlRequest.responseText);
            title = xmlDoc.documentElement.getElementsByTagName('page_title')[0];
            alert(title.childNodes[0].nodeValue);
        }
    }
于 2011-02-09T23:59:32.243 回答