AJAX 可用来与 XML 文件进行交互式通信。
实例
按钮btn添加点击事件
JavaScript 调用的服务器页面是名为 “DOM3(xml).xml” 的 PHP 文件。
页面代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<script type="text/javascript">
window.onload = function() {
var btn = document.querySelector('button');
btn.addEventListener('click',function() {
//创建JSON对象
var xmlHttp = new XMLHttpRequest();
//准备发送请求
xmlHttp.open('GET','DOM3(xml).xml',true);
//发送请求
xmlHttp.send();
//事件监听
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 && xmlHttp.status==200){
// console.log(xmlHttp.r时esponseText);
var dom = xmlHttp.responseXML
var laber = dom.querySelector('中国');
console.log(laber.children[0].children[0].innerHTML);
console.log(laber.children[1].children[0].firstChild);
console.log(laber.children[2].children[0].firstChild.wholeText);
console.log(laber.children[3].children[0].innerHTML);
}
}
});
}
</script>
</head>
<body>
<button type="button">点击</button>
</body>
</html>
对应XML文件代码:
<?xml version='1.0' encoding="utf-8"?>
<中国>
<四川>
<成都>成都</成都>
</四川>
<山西><太原>太原</太原></山西>
<陕西><西安>西安</西安></陕西>
<甘肃>
<兰州>兰州</兰州>
</甘肃>
</中国>