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

 1 <html>
 2 <head></head>
 3 <script type="text/javascript">
 4 /*---定义一个全局变量xmlHttp来创建对象----*/
 5 var xmlHttp;
 6 function createXMLHttpRequest() {
 7     if (window.ActiveXObject) {
 8         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
 9     } else if (window.XMLHttpRequest) {
10         xmlHttp = new XMLHttpRequest();
11     }
12 }
13 
14 /*---由onclick调用----*/
15 function startRequest() {
16     //创建XMLHttpRequest对象
17     createXMLHttpRequest(); 
18     
19     //当XMLHttpRequest对象的状态发生改变时,触发handleStataChange,onreadystatechange用来设置回调函数
20     xmlHttp.onreadystatechange = handleStataChange; 
21 
22     /*---open向服务器发送HTTP请求,打开xml文件夹下的Map.xml
23            规定请求的类型、URL 以及是否异步处理请求。
24         method:请求的类型;GET 或 POST
25            url:文件在服务器上的位置
26         async:true(异步)或 false(同步)
27     ---*/
28     xmlHttp.open("GET", "xml/Map.xml", true);
29 
30     xmlHttp.send(null);
31 }
32 /*---回调函数----*/
33 function handleStataChange() {
34     if (xmlHttp.readyState==4 && xmlHttp.status==200) { //表示请求完成了
35        //responseXML属性将响应提供为XML对象
36         var xmlDoc= xmlHttp.responseXML;    
37           //map获取Map.xml中id=1的那个节点。              
38        var map = xmlDoc.getElementById(1);   
39           //getElementsByTagName() 方法可返回带有指定标签名的对象的集合   
40 var src= map.getElementsByTagName("path")[0].firstChild.nodeValue  
41       alert("图片地址"+src);
42     }
43 }
44 
45 </script>
46 <body>
47 <form>
48 <input type="button" value="异步请求入口" onclick="startRequest();">
49 </form>
50 </body>
51 </html>
<?xml version="1.0" encoding="GBK"?>
<maps>
 <map id="1">
     <path>image/map/Map.jpg</path>
 </map>
</maps>

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

原文地址:https://www.cnblogs.com/michaeljunlove/p/3508047.html