简体   繁体   English

使用Javascript在HTML中加载XML

[英]Loading XML in HTML using Javascript

I am trying to load a XML file using xmlLoad 我正在尝试使用xmlLoad加载XML文件

<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”); 不确定这是否是粘贴错误,但不能确定alert(“Error”);的引号alert(“Error”); need to be straight quotes. 需要直接引号。
  2. The .xml accessor only works in IE. .xml访问器仅在IE中有效。 You need new XMLSerializer().serializeToString(xmlDoc) for other browsers. 您需要其他浏览器使用new XMLSerializer().serializeToString(xmlDoc)
  3. For IE which odes not support document.implementation.createDocument() , you can conditionally use var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 对于不支持document.implementation.createDocument() IE,可以有条件地使用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): 在IE和Firefox中都可以使用(格式正确的“ order.xml”文件与此HTML文件位于同一目录中):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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