|
EDA365欢迎您登录!
您需要 登录 才可以下载或查看,没有帐号?注册
x
1,建立文件test.html
/ A1 z O# L/ {4 T6 p& R# V
" N, `7 I# n6 A& h- u' {- <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>5 l- v: C: i6 j) D( v) G! X
" t+ n1 X. ]9 |4 l, m1 D' n
$ @- j) @+ Y4 j2 g$ S9 d& ~6 P a* S( G
2,建立js文件xmlhttpreq.js1 k6 h' W6 `5 p: p
5 @4 P* K, I% P9 T* A! T \% c
特别注意其中的在回调函数里有个setTimeout,还设置客户端的更新周期。: P, ]" r+ l; B' k( @2 F
) }8 B' A/ _8 D9 Q' Q1 U' j" h$ k
$ @4 B: ~: {& d+ b. J( e5 M- {- /*
- *创建异步访问对象
- */
- 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);
- */
' T& }2 C( \& ?6 X- R: b2 g
* ~- d, ], z; _
% u0 X# u0 b& J W
. C7 a& a. E2 Y9 i# _3 R1 h3 i3,建立linux下的cgi文件7 R1 l* I8 U8 { H, a
; A0 ~& @, `5 M& s1 I
- #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));
- }/ S/ N8 r) D0 Q
, H5 |/ ?3 A7 o% `# k h+ I
3 c% y2 ?& X0 h2 T: N0 T 生成test.cgi的可执行文件。
9 G% A/ H3 e# p! v, @8 N' l& w. r
将test.cgi和html,js文件放在服务器的www目录下。登录服务器查看,时间就是变化的,可以自动更新的。( q$ y0 }" n( }+ T) _/ i; M3 `
& |$ w# T8 ?; X& f: Z, N
. }3 F0 w7 ^& ^9 C4 k3 l6 S9 g# H( y; R8 l4 X, v! l! Q
3 p u( U1 B9 l4 m8 v1 Y
$ D3 M/ s* b4 s( [" n |
|