从 javascript 加载 xml [英] Load xml from javascript

查看:16
本文介绍了从 javascript 加载 xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对 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

这篇关于从 javascript 加载 xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆