|
|
EDA365欢迎您登录!
您需要 登录 才可以下载或查看,没有帐号?注册
x
1,建立文件test.html1 B& q2 N4 Q# Q
" Z8 E5 u8 I1 ~. a9 [9 T- <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>
( o4 _( S- K& |3 ^
. ?, p6 l* ?3 _1 h
( {% c# E9 X: Y8 m) g3 I! s( r: p0 r9 w; b# C% x
2,建立js文件xmlhttpreq.js D9 ~: |5 A2 R, {
1 U) R8 l/ A u$ ^9 F3 B
特别注意其中的在回调函数里有个setTimeout,还设置客户端的更新周期。0 ]6 ~$ V0 b5 l* m) k- z
6 M. t' X; z% j c5 ~7 b/ r
6 O3 M% V+ Q& Q3 X3 Q" ~
- /*
- *创建异步访问对象
- */
- 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);
- */
- 6 F8 l! H% B( q9 g; j) @/ x
3 J0 N" q- r1 v8 q+ X6 H5 u5 R: t9 t2 ?8 _
1 D8 r1 }$ v4 |$ R8 k5 R/ c) V3,建立linux下的cgi文件0 f. f5 s6 S$ K0 e" Z0 ]; `6 J
* W& N2 Q5 @) W3 k- #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));
- }, _" C q$ H- r; j
# {! {/ W2 r, t/ n- Z
# w* G/ [" Y. E7 w6 T
生成test.cgi的可执行文件。
+ A2 \# x- v* ]+ ^ [1 v6 ^& X& |6 d0 P4 m* {
将test.cgi和html,js文件放在服务器的www目录下。登录服务器查看,时间就是变化的,可以自动更新的。
4 ]* m( W: x" I! k o% C$ F0 G9 ?
$ T; _$ }/ k. k( |' W3 l4 A; w
, d4 P! J) d; q
* ]! V- g7 q X- o/ i7 ?6 i! g: `2 Y$ U; o; i( X( L
; R- [/ v. c% k |
|