用Ajax去读取服务器端的XML格式的数据

时间:2023-03-08 20:12:07
用Ajax去读取服务器端的XML格式的数据
 <html>
<head></head>
<script type="text/javascript">
/*---定义一个全局变量xmlHttp来创建对象----*/
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
} /*---由onclick调用----*/
function startRequest() {
//创建XMLHttpRequest对象
createXMLHttpRequest(); //当XMLHttpRequest对象的状态发生改变时,触发handleStataChange,onreadystatechange用来设置回调函数
xmlHttp.onreadystatechange = handleStataChange; /*---open向服务器发送HTTP请求,打开xml文件夹下的Map.xml
规定请求的类型、URL 以及是否异步处理请求。
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
---*/
xmlHttp.open("GET", "xml/Map.xml", true); xmlHttp.send(null);
}
/*---回调函数----*/
function handleStataChange() {
if (xmlHttp.readyState==4 && xmlHttp.status==200) { //表示请求完成了
//responseXML属性将响应提供为XML对象
var xmlDoc= xmlHttp.responseXML;
//map获取Map.xml中id=1的那个节点。
var map = xmlDoc.getElementById(1);
//getElementsByTagName() 方法可返回带有指定标签名的对象的集合
var src= map.getElementsByTagName("path")[0].firstChild.nodeValue
alert("图片地址"+src);
}
} </script>
<body>
<form>
<input type="button" value="异步请求入口" onclick="startRequest();">
</form>
</body>
</html>
<?xml version="1.0" encoding="GBK"?>
<maps>
<map id="1">
<path>image/map/Map.jpg</path>
</map>
</maps>

最后alert的结果就是:图片地址image/map/Map.jpg