通过Jquery的Ajax方法读取将table转换为Json
. 代码如下:
create table users
(
userid int identity(1,1) primary key,
username varchar(20)
)
insert into users values('bradley')
insert into users values('dan')
. 代码如下:
create table users
(
userid int identity(1,1) primary key,
username varchar(20)
)
insert into users values('bradley')
insert into users values('dan')
2. 创建jsonhelper类
. 代码如下:
public class jsonhelper
{
#region 序列化和反序列化
// 序列化
public static string jsonserializer<t>(t t)
{
// 使用 datacontractjsonserializer 将 t 对象序列化为内存流。
datacontractjsonserializer jsonserializer = new datacontractjsonserializer(typeof (t));
memorystream ms = new memorystream();
// 使用 writeobject 方法将 json 数据写入到流中。
jsonserializer.writeobject(ms, t);
// 流转字符串
string jsonstring = encoding.utf8.getstring(ms.toarray());
ms.close();
//替换json的date字符串
string p = @"\\/date\((\d+)\+\d+\)\\/";
matchevaluator matchevaluator = new matchevaluator(convertjsondatetodatestring);
regex reg = new regex(p);
jsonstring = reg.replace(jsonstring, matchevaluator);
return jsonstring;
}
public static t jsondeserialize<t>(string jsonstring)
{
//将"yyyy-mm-dd hh:mm:ss"格式的字符串转为"\/date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
matchevaluator matchevaluator = new matchevaluator(convertdatestringtojsondate);
regex reg = new regex(p);
jsonstring = reg.replace(jsonstring, matchevaluator);
datacontractjsonserializer jsonserializer=new datacontractjsonserializer(typeof(t));
// 字符串转流
memorystream ms=new memorystream(encoding.utf8.getbytes(jsonstring));
// 通过使用 datacontractjsonserializer 的 readobject 方法,将 json 编码数据反序列化为t
t obj = (t) jsonserializer.readobject(ms);
return obj;
}
public static string convertjsondatetodatestring(match match)
{
string result = string.empty;
datetime datetime=new datetime(1970,1,1);
datetime = datetime.addmilliseconds(long.parse(match.groups[1].value));
datetime = datetime.tolocaltime();
result = datetime.tostring("yyyy-mm-dd hh:mm:ss");
return result;
}
private static string convertdatestringtojsondate(match m)
{
string result = string.empty;
datetime dt = datetime.parse(m.groups[0].value);
dt = dt.touniversaltime();
timespan ts = dt - datetime.parse("1970-01-01");
result = string.format("\\/date({0}+0800)\\/",ts.totalmilliseconds);
return result;
}
#endregion
// 对象转换为json
public static string objecttojson(object obj)
{
javascriptserializer js=new javascriptserializer();
try
{
return js.serialize(obj);
}
catch (exception exception)
{
throw new exception(exception.message);
}
}
// 数据表转化为集合
public static list<dictionary<string,object>> datatabletolist(datatable dt)
{
list<dictionary<string ,object>> list=new list<dictionary<string, object>>();
foreach (datarow datarow in dt.rows)
{
dictionary<string,object> dic=new dictionary<string, object>();
foreach (datacolumn dc in dt.columns)
{
dic.add(dc.columnname,datarow[dc.columnname]);
}
list.add(dic);
}
return list;
}
// 表转换为json
public static string datatabletojson(datatable dt)
{
return objecttojson(datatabletolist(dt));
}
}
. 代码如下:
public class jsonhelper
{
#region 序列化和反序列化
// 序列化
public static string jsonserializer<t>(t t)
{
// 使用 datacontractjsonserializer 将 t 对象序列化为内存流。
datacontractjsonserializer jsonserializer = new datacontractjsonserializer(typeof (t));
memorystream ms = new memorystream();
// 使用 writeobject 方法将 json 数据写入到流中。
jsonserializer.writeobject(ms, t);
// 流转字符串
string jsonstring = encoding.utf8.getstring(ms.toarray());
ms.close();
//替换json的date字符串
string p = @"\\/date\((\d+)\+\d+\)\\/";
matchevaluator matchevaluator = new matchevaluator(convertjsondatetodatestring);
regex reg = new regex(p);
jsonstring = reg.replace(jsonstring, matchevaluator);
return jsonstring;
}
public static t jsondeserialize<t>(string jsonstring)
{
//将"yyyy-mm-dd hh:mm:ss"格式的字符串转为"\/date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
matchevaluator matchevaluator = new matchevaluator(convertdatestringtojsondate);
regex reg = new regex(p);
jsonstring = reg.replace(jsonstring, matchevaluator);
datacontractjsonserializer jsonserializer=new datacontractjsonserializer(typeof(t));
// 字符串转流
memorystream ms=new memorystream(encoding.utf8.getbytes(jsonstring));
// 通过使用 datacontractjsonserializer 的 readobject 方法,将 json 编码数据反序列化为t
t obj = (t) jsonserializer.readobject(ms);
return obj;
}
public static string convertjsondatetodatestring(match match)
{
string result = string.empty;
datetime datetime=new datetime(1970,1,1);
datetime = datetime.addmilliseconds(long.parse(match.groups[1].value));
datetime = datetime.tolocaltime();
result = datetime.tostring("yyyy-mm-dd hh:mm:ss");
return result;
}
private static string convertdatestringtojsondate(match m)
{
string result = string.empty;
datetime dt = datetime.parse(m.groups[0].value);
dt = dt.touniversaltime();
timespan ts = dt - datetime.parse("1970-01-01");
result = string.format("\\/date({0}+0800)\\/",ts.totalmilliseconds);
return result;
}
#endregion
// 对象转换为json
public static string objecttojson(object obj)
{
javascriptserializer js=new javascriptserializer();
try
{
return js.serialize(obj);
}
catch (exception exception)
{
throw new exception(exception.message);
}
}
// 数据表转化为集合
public static list<dictionary<string,object>> datatabletolist(datatable dt)
{
list<dictionary<string ,object>> list=new list<dictionary<string, object>>();
foreach (datarow datarow in dt.rows)
{
dictionary<string,object> dic=new dictionary<string, object>();
foreach (datacolumn dc in dt.columns)
{
dic.add(dc.columnname,datarow[dc.columnname]);
}
list.add(dic);
}
return list;
}
// 表转换为json
public static string datatabletojson(datatable dt)
{
return objecttojson(datatabletolist(dt));
}
}
3. 添加ashx代码文件
. 代码如下:
public class getdata : ihttphandler
{
public void processrequest(httpcontext context)
{
context.response.contenttype = "text/plain";
if (context.request["action"]=="display")
{
context.response.write(jsonhelper.datatabletojson(getallusers()));
}
}
static sqlconnection conn = new sqlconnection("server=.;database=test;uid=sa;pwd=123456");
public static datatable getallusers()
{
string sql = "select * from users";
sqldataadapter adapter = new sqldataadapter(sql, conn);
datatable dt = new datatable();
adapter.fill(dt);
return dt;
}
public bool isreusable
{
get
{
return false;
}
}
}
. 代码如下:
public class getdata : ihttphandler
{
public void processrequest(httpcontext context)
{
context.response.contenttype = "text/plain";
if (context.request["action"]=="display")
{
context.response.write(jsonhelper.datatabletojson(getallusers()));
}
}
static sqlconnection conn = new sqlconnection("server=.;database=test;uid=sa;pwd=123456");
public static datatable getallusers()
{
string sql = "select * from users";
sqldataadapter adapter = new sqldataadapter(sql, conn);
datatable dt = new datatable();
adapter.fill(dt);
return dt;
}
public bool isreusable
{
get
{
return false;
}
}
}
4. 前端调用
. 代码如下:
<html xmlns="https://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="js/jquery-1.6.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var options = {
type: 'post',
url: "/getdata.ashx",
datatype: "json",
data: { action: "display" },
success: function(data) {
var html = "<table border='2px' style='text-align:center;border-style:solid;border-width:2px;border-color:#00ff00;'><tr><td>userid</td><td>username</td></tr>";
$.each(data, function(i, result) {
html += "<tr><td>" + result["userid"] + "</td><td>" + result["username"] + "</td></tr>";
})
html += "</table>";
$("#pdata").html(html);
}
};
$.ajax(options);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<p id="pdata">
</p>
</form>
</body>
</html>
. 代码如下:
<html xmlns="https://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script src="js/jquery-1.6.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var options = {
type: 'post',
url: "/getdata.ashx",
datatype: "json",
data: { action: "display" },
success: function(data) {
var html = "<table border='2px' style='text-align:center;border-style:solid;border-width:2px;border-color:#00ff00;'><tr><td>userid</td><td>username</td></tr>";
$.each(data, function(i, result) {
html += "<tr><td>" + result["userid"] + "</td><td>" + result["username"] + "</td></tr>";
})
html += "</table>";
$("#pdata").html(html);
}
};
$.ajax(options);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<p id="pdata">
</p>
</form>
</body>
</html>
5. 效果图
6. 同样可以通过getjson方法读取数据
. 代码如下:
$.getjson("/getdata.ashx",{ action: "display" },function(data) {
var html = "<table border='2px' style='text-align:center;border-style:solid;border-width:2px;border-color:#00ff00;'><tr><td>userid</td><td>username</td></tr>";
$.each(data, function(i, result) {
html += "<tr><td>" + result["userid"] + "</td><td>" + result["username"] + "</td></tr>";
})
html += "</table>";
$("#pdata").html(html);
})
. 代码如下:
$.getjson("/getdata.ashx",{ action: "display" },function(data) {
var html = "<table border='2px' style='text-align:center;border-style:solid;border-width:2px;border-color:#00ff00;'><tr><td>userid</td><td>username</td></tr>";
$.each(data, function(i, result) {
html += "<tr><td>" + result["userid"] + "</td><td>" + result["username"] + "</td></tr>";
})
html += "</table>";
$("#pdata").html(html);
})
上一篇: 看了感觉好疼啊啊啊啊
下一篇: PHP的开源UML工具