我已经定义了这个XML文件
<?xml version="1.0" encoding="UTF-8"?>
<root>
<town>
<area>20000</area>
<population>10000</population>
</town>
</root>
&#13;
使用AJAX我加载它并尝试解析它。
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
myFunctionParsing(this);
}};
xhttp.open("GET", "towns.xml", false);
xhttp.send();
function myFunctionParsing(xml)
{
var xmlDoc = xml.responseXML;
var nodes = xmlDoc.getElementsByTagName("town");
var n = nodes[0].childNodes[0];
console.log(n.tagName);
var aDiv = document.getElementById("area");
aDiv.innerHTML = n.nodeValue;
}
&#13;
使用该脚本我想写入节点&#34;区域&#34;的div值。在一些名为&#34; area&#34;的div中。
为什么我不能写这个值?为什么n.tagName未定义?
答案 0 :(得分:0)
一些事情:
responseXML
。querySelector
很棒!用它。无需getElementsByTagName
。
function parseXML(xml) {
var area = xml.querySelector('town area');
console.log(area.textContent); // => 20000
}
var url = 'https://gist.githubusercontent.com/gabrielflorit/c618f26ac367fbaf91846efe73913c23/raw/b3c9c3e8d0f1dc747006103442b3b19bf7c91d9c/town.xml';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// If specified, responseType must be empty string or "document"
xhr.responseType = 'document';
// overrideMimeType() can be used to force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
parseXML(xhr.response);
}
}
};
xhr.send(null);
&#13;