Ajax异步(JQuery获取Json)2

本文详细介绍了如何在ASP.NET中创建一个一般处理程序来返回JSON数据,并通过JQuery实现JSON数据的获取与解析。包括了数据结构设计、返回方式对比以及JQuery的JSON数据获取方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先创建一个一般处理程序“ResponseJson.ashx”,手动拼接字符串返回Json格式:

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            List<cityInfo> cityInfos = new List<cityInfo>()
            {
              new cityInfo(){cityID=1,cityName="北京"},
              new cityInfo(){cityID=2,cityName="上海"},
              new cityInfo(){cityID=3,cityName="南京"},
              new cityInfo(){cityID=4,cityName="深圳"},
              new cityInfo(){cityID=5,cityName="广州"}
            };
           
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (cityInfo cityInfo in cityInfos)
            {
                    sb.Append("{");
                    sb.AppendFormat("\"cityID\":{0},\"cityName\":\"{1}\"", cityInfo.cityID, cityInfo.cityName);
                    sb.Append("}");
                    sb.Append(",");
            }
            string str = sb.ToString().TrimEnd(',');
            str += "]";

            context.Response.Write(str);

       // 或者将对象序列化成Json格式 和拼接相比这种方式较为死板

            //System.Web.Script.Serialization.JavaScriptSerializer JSSerializer = new JavaScriptSerializer();
            //string Json = JSSerializer.Serialize(cityInfos);
            //context.Response.Write(Json);


        }

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

    public class cityInfo
    {
        public string cityName
        {
            get;
            set;
        }

        public int cityID
        {
            get;
            set;
        }

    }

 

创建一个html页“JqueryGetJson.htm” 并且引入JQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        
    </script>
</head>
<body>
   <input type="button" value="JQuery获取Json数据" id="JqueryGetJson" />
</body>
</html>

// Jquery获取JSon

 <script type="text/javascript">
        $(function () {
            $("#JqueryGetJson").click(function () {
                $.getJSON("ResponseJson.ashx", "a=3&b=4", function (data) {
                    alert(data[1].cityName);
                });
            });
        });
    </script>

 

返回结果:“上海”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值