码迷,mamicode.com
首页 > Web开发 > 详细

Ajax异步请求一般处理程序(List)返回Json数据

时间:2015-05-29 17:52:36      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

简单实现了通过jQuery的Ajax函数异步请求一般处理程序,数据由list模拟,返回json格式的数据。

index.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="js/jquery.min.js" type="text/javascript"></script>
    <script>
        $(function () {
            $.ajax({
                type: "POST",
                url: "Handler2.ashx",
                eache: false,
                datatype: "json",
                success: function (data) {
                    var obj = eval(data);
                    $(obj).each(function (index) {
                        var val = obj[index];
                        $("body").append("<div class=‘show‘>" + val.Id + "   " + val.Name + "   " + val.Pwd + "</div>");
                    });
                },
                error: function () {
                    return;
                }
            });
        });
    </script>
</head>
<body>
    
</body>
</html>

Handler.ashx

public void ProcessRequest(HttpContext context)
{
            context.Response.ContentType = "text/plain";
            Model model1 = new Model();
            Model model2 = new Model();
            model1.Id = "c00001";
            model1.Name = "张三";
            model1.Pwd = "123456";
            model2.Id = "c00002";
            model2.Name = "李四";
            model2.Pwd = "123456";
            List<Model> list = new List<Model>();
            list.Add(model1);
            list.Add(model2);
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(list.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, list);
                    context.Response.Write(Encoding.UTF8.GetString(ms.ToArray()));
                }
            }
            catch
            {
                return;
            }
}

 

Ajax异步请求一般处理程序(List)返回Json数据

标签:

原文地址:http://www.cnblogs.com/cbmiracle/p/4538759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!