jquery+Ajax+Json绑定
整个过程对于熟练的人来说简单无比,通过简单的ajax请求获取一般处理页面返回的json字符串,在页面对返回的json字符串进行解析,并绑定到对应的列表。
页面代码:
[html]
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MyTestWebApp.JsonData.Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
<pre name="code" class="javascript">$(document).ready(function () {
$.ajax({
type: "get",
dataType: "Json",
url: "JsonHandler.ashx",
start: function () { alert("开始获取数据了") },
complete: function () { alert("获取完了") },
success: function (data) {
var t = eval(data); //强制转换一下json字符串,生成json对象
$.each(t, function (i, n) {
var row = $("#template").clone(); //克隆模板,创建一个新数据行
for (attribute in n) {
row.find("#" + attribute).html(n[attribute]); //循环json对象的属性,并赋值到数据行中对应的列,此处列的id就是相应的属性名称
}
row.appendTo($("#testTable"));
});
}
});
});
</script></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"><table id="testTable"> <th>编号</th><th>标题</th><th>内容</th> <!--数据模板--> <!--其中每一列的id就是对应记录中的列名--> <tr id="template"><td id="Id"></td><td id="title"></td><td id="content"></td></tr> <!--数据模板--></table></asp:Content>
一般处理页面代码:
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyTestWebApp.Code;
using System.Data;
namespace MyTestWebApp.JsonData
{
/// <summary>
/// JsonHandler 的摘要说明
/// </summary>
public class JsonHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
DataTable table = SqlHelper.ExecuteDataset(SqlHelper.connectionString, CommandType.Text, "select Id, title, content from Accordion").Tables[0];
context.Response.Write(JSONHelper.DataTableToJSON(table));
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
JSONHelper.cs(我是直接网上找的别人写的JSONHelper.cs)
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Data;
namespace MyTestWebApp.Code
{
/// <summary>
/// JSON帮助类
/// </summary>
public class JSONHelper
{
/// <summary>
/// 对象转JSON
/// </summary>
/// <param name="obj">对象</param>
/// <returns>JSON格式的字符串</returns>
public static string ObjectToJSON(object obj)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
return jss.Serialize(obj);
}
catch (Exception ex)
{
throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
}
}
/// <summary>
/// 数据表转键值对集合 www.2cto.com
/// 把DataTable转成 List集合, 存每一行
/// 集合中放的是键值对字典,存每一列
/// </summary>
/// <param name="dt">数据表</param>
/// <returns>哈希表数组</returns>
public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
{
List<Dictionary<string, object>> list
= new List<Dictionary<string, object>>();
foreach (DataRow dr in dt.Rows)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
{
dic.Add(dc.ColumnName, dr[dc.ColumnName]);
}
list.Add(dic);
}
return list;
}
/// <summary>
/// 数据集转键值对数组字典
/// </summary>
/// <param name="dataSet">数据集</param>
/// <returns>键值对数组字典</returns>
public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
{
Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();
foreach (DataTable dt in ds.Tables)
result.Add(dt.TableName, DataTableToList(dt));
return result;
}
/// <summary>
/// 数据表转JSON
/// </summary>
/// <param name="dataTable">数据表</param>
/// <returns>JSON字符串</returns>
public static string DataTableToJSON(DataTable dt)
{
return ObjectToJSON(DataTableToList(dt));
}
/// <summary>
/// JSON文本转对象,泛型方法
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="jsonText">JSON文本</param>
/// <returns>指定类型的对象</returns>
public static T JSONToObject<T>(string jsonText)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
return jss.Deserialize<T>(jsonText);
}
catch (Exception ex)
{
throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
}
}
/// <summary>
/// 将JSON文本转换为数据表数据
/// </summary>
/// <param name="jsonText">JSON文本</param>
/// <returns>数据表字典</returns>
public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText)
{
return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);
}
/// <summary>
/// 将JSON文本转换成数据行
/// </summary>
/// <param name="jsonText">JSON文本</param>
/// <returns>数据行的字典</returns>
public static Dictionary<string, object> DataRowFromJSON(string jsonText)
{
return JSONToObject<Dictionary<string, object>>(jsonText);
}
}
}
摘自 QQlvbo的专栏