时间:2021-07-11 08:43:40 | 栏目:jquery | 点击:次
<1>序列化对象为单个对象的时候
//Student person = new Student() { Name = "张三",Code="001" }; //JavaScriptSerializer json = new JavaScriptSerializer(); //string str = json.Serialize(person); context.Response.Write(str);
前台Jquery代码:
$(document).ready( function () { $.post("Test.ashx", function (data, status) { if (status == "success") { var person = $.parseJSON(data); alert(person.Name); }); } );
此时可以将Name属性在前台进行显示
2)序列化对象为DataTable的时候:
序列化DataTable方法:
public string SerializeDataTable(DataTable dt) { StringBuilder sb = new StringBuilder(); sb.Append("["); for (int i = 0; i < dt.Rows.Count; i++) { sb.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { sb.Append("\"" + dt.Columns[j].ColumnName + "\":\"" + dt.Rows[i][j].ToString() + "\""); if (j < dt.Columns.Count - 1) { sb.Append(","); } } sb.Append("}"); if (i < dt.Rows.Count - 1) { sb.Append(","); } } sb.Append("]"); return sb.ToString(); }
前台进行显示
$(document).ready( function () { $.post("Test.ashx", function (data, status) { if (status == "success") { var person = $.parseJSON(data); $.each(person, function (k, v) { alert(v.Name); alert(v.Code); }); } }); } );
List显示方式和DataTable的显示方法基本相同