将XML加载到DOM中并替换使用Microsoft.XMLDOM

3

我正在处理一些旧代码,许多地方都有从某个URL获取XML数据的代码。这很直接。

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";           
xmlDoc.load(url);

在一些地方
var httpRequest= new ActiveXObject("Msxml2.XMLHTTP.6.0");
httpRequest.open('GET', url, false);
httpRequest.send(null);

在大多数情况下,我们从响应的 XML 中提取结果。我已经在很多地方看到使用“Microsoft.XMLDOM”已经过时,现在更推荐使用 ActiveXObject("Msxml2.XMLHTTP.6.0")。对于其他浏览器,应该使用标准的 W3C XMLHttpRequest。这似乎没有任何问题。
问题在于加载结果 xml 字符串。我发现在使用“Microsoft.XMLDOM”时定义了 loadXML,但在 ActiveXObject("Microsoft.XMLHTTP")中却没有定义。
其他浏览器和 IE-11 推荐使用 DOMParser。
以下是我从 URL 中检索信息、解析该信息,然后尝试将 XML 字符串加载到 DOM 中的步骤。我的主要问题是我越来越困惑于何时使用适合于 Internet Explorer 的 XML 操作解决方案,或者可能是因为太晚了。
我想删除使用“Microsoft.XMLDOM”,但为了执行 loadXML,我不得不回到它。是否有更好的方法来解决这个问题?
 // Get the information use either the XMLHttpRequest or ActiveXObject
 if (window.ActiveXObject || 'ActiveXObject' in window) {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP.6.0");
        }
        else if (window.XMLHttpRequest) {
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
    }
}

httpRequest.open('GET', url, false);
httpRequest.send();

var xmlDoc = httpRequest.responseXML;

// Retrieve the XML into the DOM
var xml = xmlDoc.getElementsByTagName("XML_STRING_SETTINGS")


// Load the XML string into the DOM
if (window.DOMParser) {
    var parser = new DOMParser();
    xmlDoc = parser.parseFromString(xml, "text/xml");
}
else // code for IE
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    // is there another way to do this load? 
    xmlDoc.loadXML(xml);
}
2个回答

1

您可以采取以下步骤:

  1. 进入“Internet选项”。
  2. 选择安全选项卡。
  3. 在自定义级别下。
  4. 确保未标记“初始化并启用ActiveX控件脚本”为安全脚本,选择启用单选按钮,现在尝试运行您的代码。

我相信您的问题将得到解决。


0

我认为IE5和6的代码是

new ActiveXObject("Microsoft.XMLHTTP")

对于IE7+(以及其他浏览器)

new XMLHttpRequest();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接