简体   繁体   中英

Loading XML in HTML using Javascript

I am trying to load a XML file using xmlLoad

<script LANGUAGE=JavaScript>
if (document.implementation && document.implementation.createDocument)
{

var xmlDoc= document.implementation.createDocument("","doc",null);  
xmlDoc.async=false;                   //make sure doc is fully loaded
loaded = xmlDoc.load("order.xml");

if(!loaded)
{ 
alert(“Error”);
}
else 
{
alert(xmlDoc.xml);
} 
}

Can anybody tell me what is wrong with this code? And how can I check if my code has been loaded or not? Thanks!

Three things:

  1. Not sure if this is a pasting error, but the quotes within alert(“Error”); need to be straight quotes.
  2. The .xml accessor only works in IE. You need new XMLSerializer().serializeToString(xmlDoc) for other browsers.
  3. For IE which odes not support document.implementation.createDocument() , you can conditionally use var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); .

This works in both IE and Firefox (with a well-formed "order.xml" file in the same directory as this HTML file):

var xmlDoc = document.implementation && document.implementation.createDocument ? 
                document.implementation.createDocument("","doc",null) :
                new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false; //make sure doc is fully loaded
loaded = xmlDoc.load("order.xml");
if (!loaded) { 
    alert("Error");
}
else {
    alert(xmlDoc.xml || new XMLSerializer().serializeToString(xmlDoc));
}

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