ajax自動實時更新資料
利用ajax實現無重新整理更新資料
show.html //客戶端
<script language="JavaScript">
function GetResult() {
http_request = false;
//開始初始化XMLHttpRequest物件
if(window.XMLHttpRequest) { //Mozilla 瀏覽器
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {//設定MiME類別
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE瀏覽器
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) { // 異常,建立物件例項失敗
window.alert("不能建立XMLHttpRequest物件例項.");
return false;
}
http_request.open("POST","rand.php",false);
http_request.send();
var strResult = http_request.responseText;
RemoveRow(); //刪除以前的資料.
num1 = strResult; //欄位num1的值
row1 = tb.insertRow();
cell1 = row1.insertCell();
cell1.innerText = num1;
}
function RemoveRow() {
//保留第一行表頭,其餘資料均刪除.
var iRows = tb.rows.length;
for(var i=0;i<iRows-1;i++) {
tb.deleteRow(1);
}
}
function MyShow() {
//2秒自動重新整理一次,2秒取得一次資料.
timer = window.setInterval("GetResult()",2000);
}
</script>
<body onload="MyShow()">
<p>
</p>
<table width="47%" height="23"border="0" cellpadding="1" cellspacing="0" id="tb">
<tr>
<td>num1</td>
</tr>
</table>
get.php //服務端
<?
echo rand();
?>