Javascript利用xmlhttp获得服务器时钟的方法

clock.asp
-----------------------------------

< %
Response.Expires = -1
dim a
a=now()
Response.Write formatdatetime(a,2) & " " & formatdatetime(a,3)% >

-----------------------------------
mytime.htm
-----------------------------------

 1<html>
 2<body leftmargin="0" style="background-color:#e0d0c0" topmargin="0">
 3<table width="98%"><tr>
 4<td align="center" style="font-size:16;font-weight:bold;" width="50%">长春轨道客车股份有限公司产品计划价格计算程序</td>
 5<td align="right" width="50%">
 6<input id="myTime" size="18" style="font-size:12px;border:none;background:;" type="text"/>
 7</td>
 8</tr>
 9</table>
10</body>
11</html>
 1<script language="javascript">   
 2//简单方法,用最简单的代码实现,但是有很多错误隐患的   
 3/*   
 4function getClock()   
 5{   
 6var XmlHttp = new ActiveXObject("Msxml2.XMLHTTP")   
 7XmlHttp.Open( "POST", "clock.asp", false );   
 8XmlHttp.Send();   
 9if (XmlHttp.status == 200) myTime.value=XmlHttp.responseText;   
10window.setTimeout("getClock()","1000")   
11}   
12setInterval("getClock()",1000);   
13*/   
14</script>

如果为了能使程序的兼容性和健壮性更强,可以将mytime.htm改成如下的

-----------------------------------
mytime.htm
-----------------------------------

 1<html>
 2<body leftmargin="0" style="background-color:#e0d0c0" topmargin="0">
 3<table width="98%"><tr>
 4<td align="center" style="font-size:16;font-weight:bold;" width="50%">长春轨道客车股份有限公司产品计划价格计算程序</td>
 5<td align="right" width="50%">
 6<input id="myTime" size="18" style="font-size:12px;border:none;background:;" type="text"/>
 7</td>
 8</tr>
 9</table>
10</body>
11</html>
 1<script>   
 2//复杂方法,添加了很多检测,和错误处理   
 3var xmlhttp,alerted   
 4try {   
 5xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")   
 6} catch (e) {   
 7try {   
 8xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")   
 9} catch (E) {   
10alert("请安装Microsofts XML parsers")   
11}   
12}   
13if (!xmlhttp && !alerted) {   
14try {   
15xmlhttp = new XMLHttpRequest();   
16} catch (e) {   
17alert("你的浏览器不支持XMLHttpRequest对象,请升级");   
18}   
19}   
20function getClock()   
21{   
22if (xmlhttp) {   
23xmlhttp.Open("Get","clock.asp",true);   
24xmlhttp.onreadystatechange=RSchange;   
25xmlhttp.send();   
26}   
27}   
28setInterval( "getClock()", 1000 );   
29function RSchange()   
30{   
31if (xmlhttp.readyState==4) {   
32myTime.value = xmlhttp.responseText;   
33}   
34}   
35</script>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus