javascript - XMLHttpRequest 仅在加载 xml 文件时在本地使用 Firefox

标签 javascript xml parsing load xmlhttprequest

您好,我是社区的新手。我想请教一个问题。

我正在尝试创建一个 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/

相关文章:

javascript - 我用标签设置了复选框的样式,但我的 JavaScript 在 IE8 中不起作用

javascript - 在 Javascript SDK 中启用 OAuth 2 后,auth.sessionChange Facebook 事件停止工作

javascript - 如何使用innerItem获取ng-repeat长度?

iphone - 将 XML 解析数据保存到 NSMutableDictionary 最佳实践

php - 通过xml向mysql数据库插入数据

javascript - 如何在 JavaScript 中解析未知的 JSON 对象

javascript - JQuery 无法检测 PHP Echo 的结果

regex - 匹配包含特定词的 URL

php - 使用PHP提取正文中的每个html标签

parsing - 在没有 .proto 文件的情况下解析 Google Protocol Buffers 数据报?