开发者

JavaScript: ActiveXObject MSXML2.XMLHTTP is not returning XML on succesful loads...?

I am trying to write an Internet Explorer 8 solution for loading XML through the 'file' protocol, since the site I am building is intended to be sent as packages directly to the users. Everything I have experienced in attempting to use XMLHttpRequest to handle this seems to support what I've read online: IE8's XMLHttpRequest implementation dislikes the protocol, so I have to use an ActiveXObject to handle the loading.

I have experimented with various people's suggestions, and finally have code that appears to be successfully obtaining the file, as the responseText field is filled with the contents of the file. However, the responseXML.xml field that is supposed to hold the XML (or a text representation of it, none of the documentation I've read has been very clear) is always an empty string. How can I configure the ActiveXObject to load the XML properly?

As a bonus, could someone also explain how I am supposed to use the loaded XML once it is loading successfully? I have yet to find any documents that explain开发者_StackOverflow中文版 that bit.

Here is my 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
        }
    }
}

And here is my XML file:

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

I used the w3schools XML validator to check whether this file was somehow malformed. It is not.


This is because the local file is not served as text/xml (as a server would do) and so IE will not parse it..

you can parse it manually with the Microsoft.XMLDOM object

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);
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜