用ajax刷新服务器数据


XML文件的代码与上一例 "ajax解析服务器" 例子的文件相同.

HTMLPage_6.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              setTimeout("showPic()",5*1000);
38            }

39         }

40         
41         function getPic()
42         {
43         // 我们首先创建两个变量来存储两个元素:
44         // tempDiv  :  一个临时占位符(div)
45         // pageDiv   :  对面面上(picBar div)的引用         
46           var tempDiv=document.createElement("div");
47           var pageDiv=document.getElementById("picBar");
48            var tempDiv2=document.createElement("div");
49           if(xhr.readyState==4)
50            {
51              if(xhr.status==200)
52               {
53                 tempDiv.innerHTML=xhr.responseText;
54                 var allLinks=tempDiv.getElementsByTagName("a");
55                  linkLen=allLinks.length;
56                 //alert(tempDiv);
57                 for(i=1;i<linkLen;i+=2)
58                 {
59                   tempDiv2.appendChild(allLinks[i].cloneNode(true));
60                 }

61                 //alert(tempDiv2.innerHTML);
62                 alert(allLinks[1].innerHTML);
63                
64                 var randomImg=Math.floor(Math.random()*linkLen);
65                   //
66                 //for(i=1;i<linkLen;i++,i++)
67                   //{
68                     //pageDiv.appendChild(allLinks[i].cloneNode(true));
69                   //}
70                   pageDiv.innerHTML=allLinks[randomImg].innerHTML;
71               }

72            }

73         }

74    
</script>
75</head>
76<body>
77<p>做个用ajax刷新服务器数据的例子</p>
78<p></p><p>
79<input id="newPic" type="button" value="读取服务端的文件" />
80</p><p></p>
81<div id="picBar"></div>
82</body>
83</html>
84

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

导航