利用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();
?>