Javascript利用xmlhttp獲得伺服器時鐘的方法

來源:互聯網
上載者:User

-----------------------------------
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>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.