主頁面(要求刷新的頁面)要求每一分鐘刷新一次系統時間
<Html>
<body onload="makeRequest("getSystemTime.JSP")"> //創建httpRequest對象
<form name="dateForm">
<table>
<td colspan="2" align="center">
<div id="sysTimeShow"></div> //顯示平台系統時間
</td>
</table></form>
</body>
</Html>
getSystemTime.JSP //獲得系統的當前時間,也就是輸出結果的頁面
<%@ page language="Java" %>
<%@ page contentType="text/Html;charset=GB2312" %>
<%@ page import="Java.util.Date"%>
<%@ page import="Java.sql.Timestamp"%>
<%@ page import="Java.io.IOException"%>
<%
Date d = new Date();
Timestamp ts = new Timestamp(d.getTime());
String result = ts.toString().substring(0,16);
out.write(result,0,result.length());
%>
AJax.JS
function makeRequest(url) {
http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType){
http_request.overrideMimeType('text/XML');
}
} else if (window.ActiveXObject) {
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!http_request) {
alert("您的浏覽器不支持當前操作,請使用 IE 5.0 以上版本!");
return false;
}
//定義頁面調用的方法init,不是init();沒有();
http_request.onreadystatechange = init;
http_request.open('GET', url, true);
//禁止IE緩存
http_request.setRequestHeader("If-ModifIEd-Since","0");
//發送數據
http_request.send(null);
//每60秒刷新一次頁面
setTimeout("makeRequest('"+url+"')", 60000);
}
function init() {
if (http_request.readyState == 4) {
if (http_request.status == 0 || http_request.status == 200) {
var result = http_request.responseText;
if(result==""){
result = "系統時間獲取失敗";
}
document.getElementById ("sysTimeShow").innerHtml="平台系統時間:"+result;
} else {//http_request.status != 200
alert("請求失敗!");
}
}
}