AJAX学习

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript">
        //Methon=GET的异步
        function AjaxGet() {
            //1、创建异步对象
            var xhr = new XMLHttpRequest();
            //2、设置参数(请求方式,请求页面,是否异步)
            xhr.open("get", "/AJAX.ashx", true);
            //3、不使用缓存
            xhr.setRequestHeader("If-Modified-Since", "0");
            //4、设置数据响应返回以后的处理方式 (回调函数) 不同的浏览器对这个属性的操作有所不同
            xhr.onreadystatechange = function () {
                //业务逻辑的实现
                if (xhr.readyState == 4 && xhr.status==200) {
                    //得到响应返回的数据
                    var content = xhr.responseText;
                    document.getElementById("a").innerText = content;
                }
            }
            //5、发送请求
            xhr.send();
        }
        //Methon=POST
        function AjaxPost() {
            //1、创建异步对象
            var xhr = new XMLHttpRequest();
            //2、设置参数
            xhr.open("post", "/AJAX.ashx", true);
            //3、将参数放入Request FormData属性中in性传递
            xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
            //4、设置回调函数
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText);
                }
            }
            var id = document.getElementById("id").value;
            var name = document.getElementById("name").value;
            //5、发送请求
            xhr.send("id="+id+"&name="+name);
        }
    </script>
</head>
<body>
    <img src="http://localhost:50304/123.gif" />
    <input type="button" value="获取时间" onclick="AjaxGet()" />
    <input type="text" id="id" />
    <input type="text" id="name" />
    <input type="button" value="获取参数" onclick="AjaxPost()" />
    <h1 id="a"></h1>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Ajax
{
    /// <summary>
    /// AJAX 的摘要说明
    /// </summary>
    public class AJAX : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.HttpMethod == "GET")
            {
                context.Response.Write(DateTime.Now.ToString());
            }
            else
            {
                string id = context.Request.Form["id"];
                string name = context.Request.Form["name"];
                context.Response.Write(id + "," + name);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

posted on 2015-03-10 21:56  ianism  阅读(140)  评论(0编辑  收藏  举报

导航