一,后台获取json数据
protected void Page_Load(object sender, EventArgs e){
DataTable dt = DBhepler.GetDataTable("select top 100 * from Tstudent");
jsn = DataTable2Json(dt);
}
public string jsn = "";
public static string DataTable2Json(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
return jsonBuilder.ToString();
}
二,前台取值
var json = '<%=jsn %>';
var objJson = jQuery.parseJSON(json);
var str = "";
for (var i = 0; i < objJson.length; i++) {
str += objJson[i].id + ", "
}