也不是第一次开始使用JQuery框架,写一个Jquery+Ajax处理Json的示例、、、
建一个项目,首先添加一个test.aspx文件,代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test"%>
2
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <html xmlns="http://www.w3.org/1999/xhtml">
6 <head runat="server">
7 <title>无标题页</title>
8 <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><%--引入Jquery--%>
9 <script type="text/javascript" src="js/Ajax.js"></script><%--引入Ajax,这个JS文件要写--%>
10 <style>
11 table{width:50%; font-size:12px; border:solid 1px #ddd;}
12 tr{height:25px; line-height:25px;border:solid 1px #ddd;}
13 td{border:solid 1px #ddd;}
14 </style>
15 <script type="text/javascript">
16 $(document).ready(function(){
17 $("#BtnClick").click(function(){//BtnClick的Click事件
18 getdata();//调用方法,获取数据
19 });
20 });
21 </script>
22 </head>
23 <body>
24 <form id="form1" runat="server">
25 <div>
26 <div><input id="BtnClick" type="button" value="Click It"/></div>
27 <div id="Contents"></div>
28 </div>
29 </form>
30 </body>
31 </html>
ASP.NET 3.5已支持JSON了,在项目中引用System.Web.Extensions.dll就可以
引用该命名空间using System.Web.Script.Serialization;
使用Serialize()方法可以实现将数据对象序列化为JSON格式。但如果项目是2.0可以用另一种方法将数据对象序列化为JSON格式:
建一个一般处理程序Handler.ashx,代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 <%@ WebHandler Language="C#" Class="Handler" %>
2
3 using System;
4 using System.Web;
5 using System.Data;
6 using System.Text;
7 using System.Collections;
8 using System.Collections.Generic; // Dictionary<,> 键值对集合所需
9 using System.Web.Script.Serialization; //JavaScriptSerializer 类所需 需要 .net3.5
10
11 public class Handler : IHttpHandler {
12
13 public void ProcessRequest (HttpContext context) {
14 context.Response.ContentType = "text/plain";
15 DataSet ds = new DataSet();
16 DataTable dt = new DataTable();
17 string str_Json = "";
18
19 string method = context.Request["todo"].ToString();
20 switch (method)
21 {
22 case "getData":
23 //这里将获取的数据DataTable转成Json,这里原DataTable可以通过MVC、三层获得
24 //为简单测试,本示例动态创建一个DataTable
25 DataTable dt_New = new DataTable();
26 DataColumn dc1 = new DataColumn("ID", Type.GetType("System.String"));
27 DataColumn dc2 = new DataColumn("Name", Type.GetType("System.String"));
28 DataColumn dc3 = new DataColumn("Sex", Type.GetType("System.String"));
29 DataColumn dc4 = new DataColumn("BirthDay", Type.GetType("System.String"));
30 DataColumn dc5 = new DataColumn("Address", Type.GetType("System.String"));
31 dt_New.Columns.Add(dc1);
32 dt_New.Columns.Add(dc2);
33 dt_New.Columns.Add(dc3);
34 dt_New.Columns.Add(dc4);
35 dt_New.Columns.Add(dc5);
36 //给DataTable添加数据
37 DataRow dr_New1 = dt_New.NewRow();
38 dr_New1["ID"] = "200802520126";
39 dr_New1["Name"] = "小杨";
40 dr_New1["Sex"] = "男";
41 dr_New1["BirthDay"] = "11-10";
42 dr_New1["Address"] = "深圳";
43 dt_New.Rows.Add(dr_New1);
44 DataRow dr_New2 = dt_New.NewRow();
45 dr_New2["ID"] = "200802520122";
46 dr_New2["Name"] = "小李";
47 dr_New2["Sex"] = "女";
48 dr_New2["BirthDay"] = "11-03";
49 dr_New2["Address"] = "深圳";
50 dt_New.Rows.Add(dr_New2);
51
52 //DataTable转成Json
53 //str_Json = DataTableToJson(dt_New);//方法一
54 str_Json = DataTableToJson(dt_New,"ID,Name,Sex,BirthDay,Address");//方法二
55 break;
56 case "getProduct":
57 break;
58 default:
59 break;
60 }
61 context.Response.Write(str_Json);
62 }
63
64 ///<summary>
65 /// DataTable转Json
66 ///</summary>
67 ///<param name="dtb"></param>
68 ///<returns></returns>
69 private string DataTableToJson(DataTable dt)
70 {
71 JavaScriptSerializer jss = new JavaScriptSerializer();
72 ArrayList dic = new ArrayList();
73 foreach (DataRow dr in dt.Rows)
74 {
75 Dictionary<string, object> drow = new Dictionary<string, object>();
76 foreach (DataColumn col in dt.Columns)
77 {
78 drow.Add(col.ColumnName, dr[col.ColumnName]);
79 }
80 dic.Add(drow);
81 }
82 return jss.Serialize(dic);
83 }
84 //不用类方法转换,可用于iis不支持.net3.5时
85 ///<summary>
86 ///
87 ///</summary>
88 ///<param name="dt">DataTable数据</param>
89 ///<param name="fields">字段,可选.格式为 "ID,Name,Sex"</param>
90 ///<returns></returns>
91 public static string DataTableToJson(DataTable dt, string fields)
92 {
93 if (fields == "")
94 {
95 foreach (DataColumn dc in dt.Columns)
96 {
97 if (fields != "") fields += ",";
98 fields += dc.ColumnName;
99 }
100 }
101
102 string[] fieldsArr = fields.Split(",".ToCharArray());
103 StringBuilder Json = new StringBuilder();
104 Json.Append("[");
105 if (dt.Rows.Count > 0)
106 {
107 for (int i = 0; i < dt.Rows.Count; i++)
108 {
109 Json.Append("{");
110 for (int j = 0; j < fieldsArr.Length; j++)
111 {
112 Json.Append("\"" + fieldsArr[j] + "\":\"" + dt.Rows[i][fieldsArr[j]].ToString() + "\"");
113 if (j < fieldsArr.Length - 1)
114 Json.Append(",");
115 }
116 Json.Append("}");
117 if (i < dt.Rows.Count - 1)
118 {
119 Json.Append(",");
120 }
121 }
122 }
123 Json.Append("]");
124 return Json.ToString();
125 }
126 public bool IsReusable {
127 get {
128 return false;
129 }
130 }
131 }
做好了以上工作,接下来写Ajax方法,,新建一个Ajax.js文件,代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 function getdata()
2 {
3 var html="<table cellpadding=\"0px\" cellspacing=\"0px\"><tr><td>编号</td><td>名字</td><td>性别</td><td>生日</td><td>地址</td></tr>";
4 $.ajax({
5 type:"POST",
6 url: "Handler.ashx", //调用的url
7 data: {"todo":"getData"}, //这里是要传递的参数,格式为data: "{paraName:paraValue}",下面将会看到
8 dataType: 'json', //返回Json类型
9 success: function(data) { //回调函数,data返回值
10 $.each(data,function(index,item){
11 var bg = index % 2 == 0 ? "#eee" : "#fff";
12 html += "<tr class=\"Items\" style='background-color:" + bg + "' οnmοuseοver=\"this.style.background='#ddeeff'\" οnmοuseοut=\"this.style.background='" + bg + "'\">"
13 + "<td>" + item.ID +"</td>"
14 + "<td>" + item.Name +"</td>"
15 + "<td>" + item.Sex +"</td>"
16 + "<td>" + item.BirthDay +"</td>"
17 + "<td>" + item.Address +"</td>"
18 + "</tr>"
19 });
20 html+="</table>"
21 $("#Contents").html(html);
22 }
23 });
24
25 }
这样示例就完成了,下面是测试,运行后点击Click It的界面如下:
偶尔记录小片段、、、