Javascript如何用xmlhttp获得服务器时钟?

2013 年 5 月 11 日3060

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">
<table><tr>
<td>长春轨道客车股份有限公司产品计划价格计算程序</td>
<td>
<input type="text" size="18" />
</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">
<table><tr>
<td>长春轨道客车股份有限公司产品计划价格计算程序</td>
<td>
<input type="text" size="18" />
</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>

本文首发地址东莞奥彩网站建设:http://http://www.zjjv.com///asp/20111947.html(转载请保留)

0 0