用ajax获取时间的例子

来源:互联网 发布:张靓颖 结婚 知乎 编辑:程序博客网 时间:2024/06/03 21:32

 之前在面试过程中碰到过一道这样的题目: 用javascript语言写个ajax获取时间的例子,当时没能全部写出来,今天自己好好写了下,在vs2008下测试通过

Default.aspx 用来显示时间
        <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type ="text/javascript" src="AjaxJScript.js" >
 
</script>
    <title>无标题页</title>
   
</head>
<body>
    <form id="form1" runat="server">
   
        <input id="Button1" type="button" value="点击获取时间" onclick ="GetTime();" /> <span id="Msg"></span>
  
    </form>
</body>
</html>

 AjaxJScript.js用来实现ajax
      var xmlHttp;
var re;
//创建发出请求的对象
function createXMLHttpRequest()
{
  if(window.ActiveXObject)
  {
    xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
  }
  else if(window .XMLHttpRequest )
  {
    xmlHttp =new XMLHttpRequest ();
  }
  return xmlHttp ;
}
 
 
  function GetTime()
  {
    createXMLHttpRequest();
    var url='GetTime.aspx?'+Math.random ();
    xmlHttp.open("Get",url ,true);
    xmlHttp .onreadystatechange=ShowResult;
    xmlHttp .send(null );
   
   
  }
  function ShowResult()
  {
    if(xmlHttp.readyState==4)
    {
      if(xmlHttp.status==200)
      {
        document .getElementById ("Msg").innerHTML =xmlHttp .responseText;
       
      }
    }
   
   
  }

  GetTime.aspx 用于被js调用,在GetTime.aspx.cs的Page_Load中写如下代码
        // System.Threading.Thread.Sleep(1000); 为了看到ajax效果,将当前线程延时1000毫秒
       HttpContext .Current.Response .Write(DateTime .Now .ToShortDateString ());
       Response.End();

写完之后,可实现如下效果:在浏览器中浏览Default.aspx页面,点击Button1,将会显示当前时间

 

原创粉丝点击