Ajax异步(JQuery获取Json)2

来源:互联网 发布:乐乎lofter手机版 编辑:程序博客网 时间:2024/06/05 09:20

首先创建一个一般处理程序“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>

 

返回结果:“上海”

原创粉丝点击