1. 程式人生 > >用AJAX實現無重新整理資料讀取與顯示

用AJAX實現無重新整理資料讀取與顯示

*******資料顯示頁ajax.asp:

<script type="text/javascript">
<!--
/*
 * Author: Wintalen
 * Email: winalen (at) 163.com
 * OICQ: 83151085
 * CopyRight: www.jgzx.net
*/
//3個用於實現無重新整理資料讀取的函式
var xmlHttp ;
function createXMLHttpRequest()
{
 if(window.ActiveXObject)
 {
  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
 }
 else if(window.XMLHttpRequest) {
  xmlHttp = new XMLHttpRequest();
 }
}

function startRequest()
{
 createXMLHttpRequest();
 var url = "test.asp";
 xmlHttp.onreadystatechange = handleStateChange;
 xmlHttp.open("GET",url,true);
 xmlHttp.send(null);
 setTimeout("startRequest()",1000);
}

function handleStateChange()
{
 if(xmlHttp.readyState == 1)
 {
  document.getElementById("weather").innerHTML = "正在連線伺服器......";
 }
 else if(xmlHttp.readyState == 2)
 {
  document.getElementById("weather").innerHTML = "正在載入資訊......";
 }
 else if(xmlHttp.readyState == 4)
 {
  if(xmlHttp.status == 200)
  {
   document.getElementById("show").innerHTML = xmlHttp.responseText;
  }
  else
  {
   document.getElementById("weather").innerHTML = "資料讀取失敗,請稍後再試......";
  }
 } 
 else
 {
  document.getElementById("weather").innerHTML = "伺服器連線失敗!"; 
 }
}
//-->
</script>
<body onload="startRequest();">
<div id="show"></div>
</body> 

********資料生成頁test.asp:

<%
'下面這兩行不能少,一定要加上才能實現更新效果
Response.Buffer=true
Response.Expires=0
%>
<%=now()%>