Jquery+Ajax处理Json 转 http://c.yegeer.com/item/52648974
也不是第一次开始使用JQuery框架,写一个Jquery+Ajax处理Json的示例、、、
建一个项目,首先添加一个test.aspx文件,代码如下:
test.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><%--引入Jquery--%>
<script type="text/javascript" src="js/Ajax.js"></script><%--引入Ajax,这个JS文件要写--%>
<style>
table{width:50%; font-size:12px; border:solid 1px #ddd;}
tr{height:25px; line-height:25px;border:solid 1px #ddd;}
td{border:solid 1px #ddd;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#BtnClick").click(function(){//BtnClick的Click事件
getdata();//调用方法,获取数据
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div><input id="BtnClick" type="button" value="Click It"/></div>
<div id="Contents"></div>
</div>
</form>
</body>
</html> ASP.NET 3.5已支持JSON了,在项目中引用System.Web.Extensions.dll就可以
引用该命名空间using System.Web.Script.Serialization;
使用Serialize()方法可以实现将数据对象序列化为JSON格式。但如果项目是2.0可以用另一种方法将数据对象序列化为JSON格式
:
建一个一般处理程序Handler.ashx,代码如下:
Handler.ashx
<%@ WebHandler Language="C#" class="Handler" %>
using System;
using System.Web;
using System.Data;
using System.Text;
using System.Collections;
using System.Collections.Generic; // Dictionary<,> 键值对集合所需
using System.Web.Script.Serialization; //JavaScriptSerializer 类所需 需要 .net3.5
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string str_Json = "";
string method = context.Request["todo"].ToString();
switch (method)
{
case "getData":
//这里将获取的数据DataTable转成Json,这里原DataTable可以通过MVC、三层获得
//为简单测试,本示例动态创建一个DataTable
DataTable dt_New = new DataTable();
DataColumn dc1 = new DataColumn("ID", Type.GetType("System.String"));
DataColumn dc2 = new DataColumn("Name", Type.GetType("System.String"));
DataColumn dc3 = new DataColumn("Sex", Type.GetType("System.String"));
DataColumn dc4 = new DataColumn("BirthDay", Type.GetType("System.String"));
DataColumn dc5 = new DataColumn("Address", Type.GetType("System.String"));
dt_New.Columns.Add(dc1);
dt_New.Columns.Add(dc2);
dt_New.Columns.Add(dc3);
dt_New.Columns.Add(dc4);
dt_New.Columns.Add(dc5);
//给DataTable添加数据
DataRow dr_New1 = dt_New.NewRow();
dr_New1["ID"] = "200802520126";
dr_New1["Name"] = "小杨";
dr_New1["Sex"] = "男";
dr_New1["BirthDay"] = "11-10";
dr_New1["Address"] = "深圳";
dt_New.Rows.Add(dr_New1);
DataRow dr_New2 = dt_New.NewRow();
dr_New2["ID"] = "200802520122";
dr_New2["Name"] = "小李";
dr_New2["Sex"] = "女";
dr_New2["BirthDay"] = "11-03";
dr_New2["Address"] = "深圳";
dt_New.Rows.Add(dr_New2);
//DataTable转成Json
//str_Json = DataTableToJson(dt_New);//方法一
str_Json = DataTableToJson(dt_New,"ID,Name,Sex,BirthDay,Address");//方法二
break;
case "getProduct":
break;
default:
break;
}
context.Response.Write(str_Json);
}
///<summary>
/// DataTable转Json
///</summary>
///<param name="dtb"></param>
///<returns></returns>
private string DataTableToJson(DataTable dt)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = new ArrayList();
foreach (DataRow dr in dt.Rows)
{
Dictionary<string, object> drow = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
drow.Add(col.ColumnName, dr[col.ColumnName]);
}
dic.Add(drow);
}
return jss.Serialize(dic);
}
//不用类方法转换,可用于iis不支持.net3.5时
///<summary>
///
/// </summary>
///<param name="dt">DataTable数据</param>
///<param name="fields">字段,可选.格式为 "ID,Name,Sex"</param>
///<returns></returns>
public static string DataTableToJson(DataTable dt, string fields)
{
if (fields == "")
{
foreach (DataColumn dc in dt.Columns)
{
if (fields != "") fields += ",";
fields += dc.ColumnName;
}
}
string[] fieldsArr = fields.Split(",".ToCharArray());
StringBuilder Json = new StringBuilder();
Json.Append("[");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = 0; j < fieldsArr.Length; j++)
{
Json.Append("\"" + fieldsArr[j] + "\":\"" + dt.Rows[i][fieldsArr[j]].ToString() + "\"");
if (j < fieldsArr.Length - 1)
Json.Append(",");
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]");
return Json.ToString();
}
做好了以上工作,接下来写Ajax方法,,新建一个Ajax.js文件,代码如下:
Ajax.js
function getdata()
{
var html="<table cellpadding=\"0px\" cellspacing=\"0px\"><tr><td>编号</td><td>名字</td><td>性别</td><td>生日
</td><td>地址</td></tr>";
$.ajax({
type:"POST",
url: "Handler.ashx", //调用的url
data: {"todo":"getData"}, //这里是要传递的参数,格式为data: "{paraName:paraValue}",下面将会看到
dataType: 'json', //返回Json类型
success: function(data) { //回调函数,data返回值
$.each(data,function(index,item){
var bg = index % 2 == 0 ? "#eee" : "#fff";
html += "<tr class=\"Items\" style='background-color:" + bg + "'
onmouseover=\"this.style.background='#ddeeff'\" onmouseout=\"this.style.background='" + bg + "'\">"
+ "<td>" + item.ID +"</td>"
+ "<td>" + item.Name +"</td>"
+ "<td>" + item.Sex +"</td>"
+ "<td>" + item.BirthDay +"</td>"
+ "<td>" + item.Address +"</td>"
+ "</tr>"
});
html+="</table>"
$("#Contents").html(html);
}
});
}