从 javascript 加载 xml

2022-01-15 00:00:00 xml xmlhttprequest javascript

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

Totally new to XML and I've been struggling on this very simple objective for too long (though I can find enough on the internet about it). Just need the values out of this xml file:

<?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 数据:

In javascript, I use this code to get the xml data:

// 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');

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

No result though, cause I'm not seeing the alert..

推荐答案

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

Your server isn't returning the appropriate Content-Type header. The responseXML property only works if the server returns a Content-Type: text/xml or similar +xml header.

查看 Ajax 模式:

服务只需要输出一个 XML Content-type header...

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

来自 w3c:

如果最终 MIME 类型不为 null,则 text/xml、application/xml 和不以 +xml 结尾 [...] 返回 null.

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

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

If you have no access to the server and can't change the Content-Type header, use the overrideMimeType function to force the XMLHttpRequest to treat the response as 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

相关文章