简单的Ajax

ajax获取时间的html代码

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript">
        window.onload = function () {
            document.getElementById("btnGetTime").onclick = function () {
                //向服务器请求  时间
                //1.创建异步对象(小浏览器)
                var xhr = new XMLHttpRequest();
                //2.设置参数
                xhr.open("get", "GetTime.ashx?name=lxz", true);
                //3.让get请求不从浏览器获取缓存数据
                xhr.setRequestHeader("If-Modified", "0");
                //3.设置回调函数
                xhr.onreadystatechange = function () {
                    //3.1当完全接收完响应报文后,并且 响应状态码为200的时候
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        //3.2获取响应报文体内容
                        var res = xhr.responseText;
                        alert(res);
                    }
                };
                //4.发送异步请求
                xhr.send(null);
            };
            document.getElementById("btnPostTime").onclick = function () {
                //向服务器请求  时间
                //1.创建异步对象(小浏览器)
                var xhr = new XMLHttpRequest();
                //2.设置参数
                xhr.open("post", "GetTime.ashx", true);

                //post请求不会使用浏览器端请求。。。所以不需要下面这段代码
                ////3.让get请求不从浏览器获取缓存数据
                //xhr.setRequestHeader("If-Modified", "0");


                //设置请求报文体的  编码格式(设置  表单默认编码格式)
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                //3.设置回调函数
                xhr.onreadystatechange = function () {
                    //3.1当完全接收完响应报文后,并且 响应状态码为200的时候
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        //3.2获取响应报文体内容
                        var res = xhr.responseText;
                        alert(res);
                    }
                };
                //4.发送异步请求
                //xhr.send();//第一种方式{name:"lxz"})
                xhr.send("name=lxz");
            };
        };
    </script>
</head>
<body>
    <form enctype="application/x-www-form-urlencoded"></form>
    <input type="button" id="btnGetTime" value="get获取服务器时间" />
    <input type="button" id="btnPostTime" value="post获取服务器时间" />
    <img src="img/1.gif" />""
</body>

 

 GetTime.ashx页面代码

 context.Response.ContentType = "text/plain";
            //接收浏览器  Ajax  方式发送过来的  get参数
            //string strName = context.Request.QueryString["name"];
            //无论get还是post都能接收
            string strName = context.Request.Params["name"];
            //休息1s钟
            System.Threading.Thread.Sleep(1000);
            //输出响应报文
            context.Response.Write(DateTime.Now.ToString()+",name="+strName);

 

 这时我们在浏览器中查看时就会发现图片保持动不变,会弹出时间提示框

posted @ 2014-04-17 22:56  李小争  阅读(194)  评论(0编辑  收藏  举报