简体   繁体   中英

How to load xml-file with JavaScript in non-IE browsers?

I have the next code which works fine in IE:

xml=new ActiveXObject("MSXML2.DOMDocument");
xml.async=false
xml.load("docs.xml")

How to do the same (without AJAX) in other browsers?

Actually, without AJAX does make sense if your HTML and JavaScript will be running from a local media since you can't do XMLHttp requests to file:// . In such cases you have to resort to other methods to load the XML data than the standard ones used for AJAX requests.

In Gecko browsers (Mozilla Firefox and alike) you can do it using something like

xml = document.implementation.createDocument("","",null);
xml.load("docs.xml", "text/xml");

It is a known issue that document.implementation.createDocument isn't implemented on Safari/Chrome/Webkit so you'll likely have to resort to loading the content in an iframe and accessing the contentDocument object of the iframe.

Um... you can't do that with Javascript but without AJAX. You're already using AJAX with the code you have (Microsoft's version of AJAX, anyway).

I suggest reading the Mozilla tutorial on AJAX for the cross-browser equivalent of your code.

您可以在Firefox中使用DOMParser

Without ajax makes sense assuming you already have the text available. xml.load(...) still uses an async call to fetch the document. If you want a cross-browser XML parser, you'll want to try:

if (window.DOMParser)
{
  parser=new DOMParser();
  xmlDoc=parser.parseFromString(text,"text/xml");
}
else // Internet Explorer
{
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(text); 
}

Depending on your use case, working with local files, you may consider doing it the other way round: load the "docs.xml" file itself, and apply an XSLT stylesheet using a processing-instruction to render it as HTML.

How to transform XML into XHTML using XSLT

I think you feel difficult when using AJAX.

In your case, it contains more risks about security and nowaday, developer will not use this tech because it call component of window, and IE prefer it than other browsers.

So, you should research more info about ajax, such as jquery or prototype, mootool, they are very powerful ajax framework and they can easily apply your demand.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM