|
|
EDA365欢迎您登录!
您需要 登录 才可以下载或查看,没有帐号?注册
x
1,建立文件test.html( [7 t# L' O! G
4 d- ^4 e# R1 p
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
- <title>liuxizhen</title>
- <script language="JavaScript" src="xmlhttpreq.js"></script>
- </head>
- <body>
- <h3>获取服务器当前时间</h3>
- <p>服务器当前时间是:<div id="current_time"></div></p>
- <input type="button" value="提交" οnclick="sender()" />
- </body>
- </html>
$ }* |6 r+ b0 c + u/ b: U$ H) A/ p3 M: h
1 Y3 B6 c; e* v. q0 n; w O1 k
/ ?( K: Y0 o; z4 {( k2,建立js文件xmlhttpreq.js6 _+ i6 @6 b" L: |' h4 I& h
% O! o1 \* K/ ?8 o5 P4 G+ D
特别注意其中的在回调函数里有个setTimeout,还设置客户端的更新周期。
0 ~/ e% Y% m+ C$ V$ |
; B& }+ T9 z2 t3 W5 v
M. ]; r; i- g$ h- /*
- *创建异步访问对象
- */
- function createXHR()
- {
- var xhr;
- try
- {
- xhr = new ActiveXObject("Msxml2.XMLHTTP");
- }
- catch (e)
- {
- try
- {
- xhr = new ActiveXObject("Microsoft.XMLHTTP");
- }
- catch(E)
- {
- xhr = false;
- }
- }
- if (!xhr && typeof XMLHttpRequest != 'undefined')
- {
- xhr = new XMLHttpRequest();
- }
- return xhr;
- }
- /*
- *异步访问提交处理
- */
- function sender()
- {
- xhr = createXHR();
- if(xhr)
- {
- xhr.onreadystatechange=callbackFunction;
- //test.cgi后面跟个cur_time参数是为了防止Ajax页面缓存
- xhr.open("GET", "test.cgi?cur_time=" + new Date().getTime());
- xhr.send(null);
- }
- else
- {
- //XMLHttpRequest对象创建失败
- alert("浏览器不支持,请更换浏览器!");
- }
- }
- /*
- *异步回调函数处理
- */
- function callbackFunction()
- {
- if (xhr.readyState == 4)
- {
- if (xhr.status == 200)
- {
- var returnValue = xhr.responseText;
- if(returnValue != null && returnValue.length > 0)
- {
- document.getElementById("current_time").innerHTML = returnValue;
- setTimeout(sender, 1000);
- }
- else
- {
- alert("结果为空!");
- }
- }
- else
- {
- alert("页面出现异常!");
- }
- }
- }
- /*
- setTimeout(sender, 1000);
- */
- x/ s6 m! t( U8 X 4 G9 j R$ w a1 z. f6 U9 }& @9 t
* b7 S) r9 Q' b" h6 Z Y/ y; {
/ `4 A# q1 m' |0 v' I& ]; ~3,建立linux下的cgi文件
1 }5 U9 P: t- N( G% Z6 _( ]! B5 X+ t; @
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- int main(void)
- {
- time_t current;
- struct tm *timeinfo;
- time(¤t);
- timeinfo = localtime(¤t);
- //这一句一定要加,否则异步访问会出现页面异常
- printf("Content type: text/html\n\n");
- printf("%s", asctime(timeinfo));
- }
0 T( p! r! h6 ?1 h; I $ f! C) R6 m7 a3 o3 a1 v0 T0 S
9 k$ h( O6 W4 `; `/ Q 生成test.cgi的可执行文件。
4 N- h# b* L" t0 n* m! g: A0 Q, J3 Z# `2 Q! ?% [0 |+ }$ g1 W* i
将test.cgi和html,js文件放在服务器的www目录下。登录服务器查看,时间就是变化的,可以自动更新的。: O. ~' X/ p! b
, k& L* G O7 n5 M4 a1 c5 C, {7 Z) b, D% ?; w. w
c2 O& a* Z4 j. v! x3 |3 l! I
; L' b" K9 z' [: ~2 C2 e& }
5 i' \& |# b' C- d$ V' `. A
|
|