本文转自:
效果如图:
一、声明talbe
二、JS绑定Table值
当前使用的是服务端分页 sidePagination: "server" 。根据数据库的查询结果绑定table数据每次只查询当前显示的行,适合数据量大的程序;还有一种是客户端分页,是一次性查询出所有的内容,然后再分页,客户端分页的模式适合数据量小的程序。client模式的分页还没研究,这里就不演示了。
三、后台代码:分页需要加上total和row属性,另外需要获取前台传入的rows和page值,来查询需要的行数。
string sql = ""; DataSet ds = new DataSet(); public void ProcessRequest(HttpContext context) { string output = ""; string action = context.Request["action"].ToString();switch (action) { case "GetJson": DataTable dt = getData(context); string str = DataTableToJsonWithStringBuilder(dt); output = "{\"total\":" + getCout(context) + ",\"rows\":" + str + "}"; break;default: break; } context.Response.ContentType = "text/plain"; context.Response.Write(output); }public string GetJson(HttpContext context) { DataTable dt = getData(context); return DataTableToJsonWithStringBuilder(dt); } public DataTable getData(HttpContext context) { int rows = Convert.ToInt32(context.Request["rows"]);//显示行数 int page = Convert.ToInt32(context.Request["page"]);//页码 int starNum = rows * page - rows + 1;//开始行数 int endNum = rows * page;//结束行数 string sql = "select * from (select row_number() over(order by @@servername) as rownum,* from yhgl)a where rownum between " + starNum + " and " + endNum + ""; DataSet ds = pub.GetDataset(sql, "xinxi"); return ds.Tables["xinxi"]; } public int getCout(HttpContext context) { string sql = "select count(*) count from yhgl"; DataSet ds = pub.GetDataset(sql, "xinxi"); return Convert.ToInt32(ds.Tables["xinxi"].Rows[0]["count"]); } public string DataTableToJsonWithStringBuilder(DataTable table) { var jsonString = new StringBuilder(); if (table.Rows.Count > 0) { jsonString.Append("["); for (int i = 0; i < table.Rows.Count; i++) { jsonString.Append("{"); for (int j = 0; j < table.Columns.Count; j++) { if (j < table.Columns.Count - 1) { jsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\","); } else if (j == table.Columns.Count - 1) { jsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\""); } } if (i == table.Rows.Count - 1) { jsonString.Append("}"); } else { jsonString.Append("},"); } } jsonString.Append("]"); } return jsonString.ToString(); }