|
|
EDA365欢迎您登录!
您需要 登录 才可以下载或查看,没有帐号?注册
x
1,建立文件test.html
9 y& f T: d5 j2 K0 C7 e
7 p* ~! r3 W( V- <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>
+ g9 M4 _7 }, m6 e4 r3 m! ?. d9 E
6 `5 z+ N. ]7 r* F4 ~- W# n% z" c6 z" k4 J4 U
: f- `0 n. G' I
2,建立js文件xmlhttpreq.js" _/ B0 @9 s% l: ~" d+ |, v
/ l7 A% G( S U* F
特别注意其中的在回调函数里有个setTimeout,还设置客户端的更新周期。
3 e& Y/ ?0 v: _
5 A: H5 {) i3 Q) p& d0 T. v+ n6 U0 `4 v; R' r
- /*
- *创建异步访问对象
- */
- 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);
- */
- 0 n6 j+ C1 ]9 e; O) v" K, i2 \5 ?
) @- C/ z) C+ j
0 t! h, R9 D: K* |; O ]$ A0 _+ u% g2 K
; g* a& R- I4 p$ w) j3,建立linux下的cgi文件3 E" A* K- Z8 E0 B' Z7 Z
h2 p: t9 C& ?) D8 a) ~- #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));
- }" h# e f+ N1 s- H2 O* g
! ?# ]7 t) M5 R. K% h, d: ?; p1 w5 v5 o* b, M3 p
生成test.cgi的可执行文件。
& P" E/ U* F, N8 @) J/ x5 O
1 j8 t9 U' H8 ?4 v3 R2 n' Q) S将test.cgi和html,js文件放在服务器的www目录下。登录服务器查看,时间就是变化的,可以自动更新的。+ x; R" M5 K) z! i
+ o4 C0 t+ O, @* [9 Y. ]8 i( C& I2 K& r
S; f/ b* c3 a1 I: {9 `
1 Z2 j: u$ q+ I! X* z( C; {# W7 }& K0 _8 @. C$ I
|
|