Ajax请求的四种方式

       一般情况下我们做异步都是直接用的是Jquery封装的XmlHttpRequest,不过有时候还是要知道一下这个类的写法。如果要写一下XmlHttpRequest可以这样写:

 <script src="../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnDate").click(function () {
                var ajax;
                //第一步:创建异步请求的核心的对象:
                if (XMLHttpRequest) {
                    ajax = new XMLHttpRequest("XMLHttpRequest");//ie7,ie8,谷歌,火狐这样创建
                }
                else {
                    ajax = new ActiveXObject();//ie5,ie6需要这样创建
                }
                //第二步:设置请求对象跟后台哪个页面进行交互
                ajax.open("post", "firstAjax.ashx", true);
                ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                //第三步:发送请求
                //Post通过此来传递参数,socket请求通过封装报文开始发送socket
                ajax.send("ip=3&renp=100");

                //第四步:后台返回数据后,会调用此方法,回调函数
                ajax.onreadystatechange = function () {
                    if (ajax.readyState == 4) {
                        alert(ajax.responseText);
                    }
                }
            })
        })
    </script>
</head>
<body>
    <input type="button" id="btnDate" name="btnDate" value="时间" />
</body>
</html>

那么一般处理程序就写一句话: context.Response.Write(DateTime.Now.ToShortDateString());
前台页面就只打印一下时间

如果一般处理程序返回的是一个Json数据,前台就需要处理一下,这里简单的把一般处理程序写一下

 public class Ajax : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            List<City> list = new List<City>() { 
                new City(){CityId=1,CityName="襄樊"},
                new City(){CityId=2,CityName="宜昌"},
                new City(){CityId=3,CityName="随州"}
            };
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (var item in list)
            {
                sb.Append("{");
                sb.AppendFormat(""CityId":"{0}","CityName":"{1}"", item.CityId, item.CityName);
                sb.Append("},");
            }
            String str = sb.ToString().TrimEnd(',');
            str += "]";
            context.Response.Write(str);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public class City   //内部类
        {
            public string CityName { get; set; }
            public int CityId { get; set; }
        }
    }

这里也可以写成序列化的方式,更简洁一些,

 JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            string json = javaScriptSerializer.Serialize(list);
            context.Response.Write(json);

  

序列化的话就把所有的数据都序列了,拼接的方式就会显得灵活一点

第一种:直接获取Json数据

   //直接获取Json数据
            $("#GetJson").click(function () {
                $.getJSON("../Ajax/four.ashx", "a=3&b=4", function (data) {

                    alert(data[1].CityName);
                });
            });

第二种:通过Get/Post请求:

   //t通过Get请求
            $("#btnGet").click(function () {
                $.get("four.ashx", "d=3&id=4", function (data) {
                    alert(data);
                });
            });

            //通过Post更直接
            $("#btnPost").click(function () {
                $.post("four.ashx", "{d: 33, demo: 'shit'}", function (data) {
                    alert(data[2].CityName);
                }, "json");
            });

如果要写的话,这种写法代码会更短,更方便一些

第三种:就是就可以Get也可以Post,也是目前用的人最多的

  $("#btnZong").click(function () {
                $.ajax({
                    url: "four.ashx",
                    data: "a=3&b=4",
                    type: "Post",
                    success: function (data) {
                        alert(data);
                        $("#zong").text(data);
                    },
                    error: function () {
                        alert("error");
                    }
                });
            });

第四种:Load一下,这种写法更适合于那种在一个页面直接展示

  $("#btnLoad").click(function () {
                $("#zong").load("four.ashx", { id: 333 }, function (data) {
                    alert(data);
                });
            })


注:html标签:

<body>
    <input type="button" name="name" value="直接获得Json数据" id="GetJson"/>
    <input type="button" name="name" value="Get" id="btnGet"/>
    <input type="button" name="name" value="JQ Post" id="btnPost"/>  
    <input type="button" name="name" value="Jquery 综合性的" id="btnZong"/>   
    <input type="button" name="name" value="JQ Load" id="btnLoad"/> <br />
    <div id="zong"></div>
</body>
原文地址:https://www.cnblogs.com/tuibian/p/3563844.html