ajax 中解析服务器数据


此例利用ajax取得XML文件中的图片.(实现了利用ajax解析服务器数据的功能)
一共包含二个文件:HTMLPage_5.htm 和 htmlPage_5.xml 文件;

HTMLPage_5.htm 代码如下  :
 1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2<html xmlns="http://www.w3.org/1999/xhtml" >
 3<head>
 4    <title>无标题页</title>
 5    
 6    <script language="javascript" type="text/javascript">

 7       
 8       window.onload=
initAll;
 9       var
 xhr;
10
       
11       function
 initAll()
12         
{
13           document.getElementById("newPic").onclick=
showPic;
14           return false
;
15         }

16         
17         function
 makeRequest()
18         
{
19           if
(window.XMLHttpRequest)
20             
{
21               xhr=new
 XMLHttpRequest();
22             }

23             else if(window.ActiveXObject)
24             
{
25               xhr=new ActiveXObject("Microsoft.XMLHTTP"
);
26             }

27         }

28         
29         function
 showPic()
30         
{
31
            makeRequest();
32            if
(xhr)
33            
{
34              xhr.onreadystatechange=
getPic;
35              xhr.open("get","htmlPage_5.xml",true
);
36              xhr.send(null
);
37            }

38         }

39         
40         function
 getPic()
41         
{
42         // 我们首先创建两个变量来存储两个元素:

43         // tempDiv  :  一个临时占位符(div)
44         // pageDiv   :  对面面上(picBar div)的引用         
45           var tempDiv=document.createElement("div");
46           var pageDiv=document.getElementById("picBar"
);
47           if(xhr.readyState==4
)
48            
{
49              if(xhr.status==200
)
50               
{
51                 tempDiv.innerHTML=
xhr.responseText;
52                 //alert(tempDiv);

53                 var allLinks=tempDiv.getElementsByTagName("a");
54                   linkLen=
allLinks.length;
55                 for(i=1;i<linkLen;i++,i++
)
56                   
{
57                     pageDiv.appendChild(allLinks[i].cloneNode(true
));
58                   }

59               }

60            }

61         }

62    
</script>
63</head>
64<body>
65<p>做个用ajax解析服务器的例子</p>
66<p></p><p>
67<input id="newPic" type="button" value="读取服务端的文件" />
68</p><p></p>
69<div id="picBar"></div>
70</body>
71</html>
72


htmlPage_5.xml  代码如下:

 
 1<?xml version="1.0" encoding="utf-8" ?>
 2<myPic>
 3  <entry>
 4  <name>zhougjun</name>
 5  <content type="html"">
 6    <href="www.163.com">www.163.com</a>
 7    posted photos: 
 8    <href="www.qq.com">

 9      <img src="classmates/1.jpg" />
10    </a>
11           
12   </content>

13  </entry>
14
15  <entry>

16    <name>gongxu</name>
17    <content type="html"">
18      <href="www.163.com">www.163.com</a>
19      posted photos:
20      <href="www.qq.com">

21        <img src="classmates/2.jpg" />
22      </a>
23
24    </content>

25  </entry>
26</myPic>
27

posted on 2008-05-04 10:11  鱼跃于渊  阅读(177)  评论(0编辑  收藏  举报

导航