您好,我是社区的新手。我想请教一个问题。
我正在尝试创建一个 HTML5 模板来加载和进行测验。我有包含问题和答案的 xml 文件,我正在尝试将其加载到我的模板中。
我使用的代码是这样的:
加载 xml 文件
// The Script that loads the XML File Locally only works in Firefox for now
function loadXMLDoc(XMLname) {
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", XMLname, false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(XMLname);
return xmlDoc;
}
else {
xmlhttp = new XMLHttpRequest();
//Open the file using the GET routine
xmlhttp.open("GET", XMLname, false);
//Send request
xmlhttp.send(null);
//xmlDoc holds the document information now
return xmlDoc.responseXML;
}
alert("Error loading document!");
return null;
}
将内容传递到我的 HTML5 模板
xmlDoc=loadXMLDoc("test"+file+".qxml");
<小时/>
我的问题是未检索 xml 文件中的数据。在服务器或任何其他浏览器上时,xmlDoc 变量显示为 null。
你能给我指出一些方向吗,因为我是 Javascript xmlhttprequest 方法的新手。非常感谢您抽出时间。
文件扩展名不是 xml(而是 .qxml)。问题在于文件 .qxml 的扩展名。那么有没有办法绕过这个并使用我的扩展 qxml 而不是 xml ?
最佳答案
尝试override the mime type由服务器返回,并告诉浏览器该数据是XML。
// The Script that loads the XML File Locally only works in Firefox for now
function loadXMLDoc(XMLname) {
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", XMLname, false);
xmlDoc.overrideMimeType('text/xml');
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(XMLname);
return xmlDoc;
}
else {
xmlhttp = new XMLHttpRequest();
//Open the file using the GET routine
xmlhttp.open("GET", XMLname, false);
xmlhttp.overrideMimeType('text/xml');
//Send request
xmlhttp.send(null);
//xmlDoc holds the document information now
return xmlDoc.responseXML;
}
alert("Error loading document!");
return null;
}
关于javascript - XMLHttpRequest 仅在加载 xml 文件时在本地使用 Firefox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13285532/