读取从AJAX返回的XML

时间:2016-09-02 20:51:13

标签: javascript ajax xml

我已经定义了这个XML文件



<?xml version="1.0" encoding="UTF-8"?>
<root>
<town>
   <area>20000</area>
   <population>10000</population>
</town>
</root>
&#13;
&#13;
&#13;

使用AJAX我加载它并尝试解析它。

&#13;
&#13;
<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;
&#13;
&#13;

使用该脚本我想写入节点&#34;区域&#34;的div值。在一些名为&#34; area&#34;的div中。

为什么我不能写这个值?为什么n.tagName未定义?

1 个答案:

答案 0 :(得分:0)

一些事情:

  • 我使用的是MDN&#39; XMLHttpRequest example,它显示了如何覆盖mime类型以强制它将响应解析为XML。这样你就不必做responseXML
  • querySelector很棒!用它。无需getElementsByTagName

&#13;
&#13;
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;
&#13;
&#13;