問題描述
對 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!