javascript - 从 javascript 加载 xml

标签 javascript xml xmlhttprequest

对 XML 完全陌生,我已经为这个非常简单的目标苦苦挣扎了太久(尽管我可以在 Internet 上找到足够多的关于它的信息)。只需要这个 xml 文件中的值:

<?xml version="1.0" encoding="UTF-8"?>
<materials>
    <basic>
        <uurloon>10</uurloon>
        <setloon>100</setloon>
    </basic>
    <extra>
        <geluid>150</geluid>
        <ledset>35</ledset>
        <strobo>20</strobo>
        <laser>50</laser>
    </extra>
</materials>

在 javascript 中,我使用这段代码来获取 xml 数据:

// load xml file
if (window.XMLHttpRequest) {
   xhttp = new XMLHttpRequest();
} else {    // IE 5/6
   xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xhttp.open("GET", "pricing.xml", false);
xhttp.send();
xmlDoc = xhttp.responseXML; 

var uurloon = xmlDoc.getElementsByTagName("uurloon")[0].childNodes[0].text;
var setloon = xmlDoc.getElementsByTagName("setloon")[0].childNodes[0].text
alert('end');

虽然没有结果,因为我没有看到警报..

最佳答案

您的服务器未返回适当的 Content-Type header 。 responseXML 属性仅在服务器返回 Content-Type: text/xml 或类似的 +xml header 时才有效。

See Ajax Patterns :

The service just needs to output an XML Content-type header...

From the w3c :

If final MIME type is not null, text/xml, application/xml, and does not end in +xml [...] return null.

如果您无法访问服务器并且无法更改 Content-Type header ,请使用 overrideMimeType 函数强制 XMLHttpRequest 将响应视为 text/xml:

if (window.XMLHttpRequest) {
   xhttp = new XMLHttpRequest();
} else {    // IE 5/6
   xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xhttp.overrideMimeType('text/xml');

xhttp.open("GET", "pricing.xml", false);
xhttp.send(null);
xmlDoc = xhttp.responseXML;

var uurloon = xmlDoc.getElementsByTagName("uurloon")[0].childNodes[0].text;
var setloon = xmlDoc.getElementsByTagName("setloon")[0].childNodes[0].text
alert('end');

引用:http://blog-rat.blogspot.com/2010/11/xmlhttprequestresponsexml-returns-null.html

关于javascript - 从 javascript 加载 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249155/

相关文章:

javascript - jQuery 不会在页面加载时 append 克隆

php - Jquery AJAX 实时输出?

javascript - 向页面上的所有 AJAX 请求添加 "hook"

javascript - JavaScript 中的 XMLHttpRequest 是什么类型?

javascript - 使用 jquery/css 隐藏元素

javascript - 将 requestAnimationFrame 分配给对象变量时出现类型错误

javascript - 使用javascript检查文件是否存在

python-3.x - 有没有办法使用 ElementTree 注册多个命名空间

java - 将数据加载到 Java GUI 中

java - AlarmManager 在 Android 中不工作