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

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

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

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

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

 

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

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

<html>
<body topmargin="0" leftmargin="0"  style="background-color:#e0d0c0">
<table width="98%"><tr>
 <td align="center" width="50%" style="font-size:16;font-weight:bold;">长春轨道客车股份有限公司产品计划价格计算程序</td>
 <td width="50%" align="right">
    <input type="text" style="font-size:12px;border:none;background:;" size="18" id="myTime" />
 </td>
</tr>
</table>
</body>
</html>

<script>
//复杂方法,添加了很多检测,和错误处理
var xmlhttp,alerted
  try {
  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
 } catch (e) {
  try {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  } catch (E) {
     alert("请安装Microsofts XML parsers")
  }
 }
if (!xmlhttp && !alerted) {
 try {
  xmlhttp = new XMLHttpRequest();
 } catch (e) {
  alert("你的浏览器不支持XMLHttpRequest对象,请升级");
 }
}
function getClock()
{
if (xmlhttp) {
  xmlhttp.Open("Get","clock.asp",true);
  xmlhttp.onreadystatechange=RSchange; 
  xmlhttp.send();
  }
}
setInterval( "getClock()", 1000 );
function RSchange()
{
  if (xmlhttp.readyState==4) {
  myTime.value = xmlhttp.responseText;
  }
 }
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值