ajax+json+ashx实现一个页面多个tab的分页
1:项目功能需求:我的荣誉、审核中的荣誉、审核通过的荣誉在一个页面分别作列表展示。每个tab都需要分页,对实现的功能做个简单总结。
2:前台页面:引用的DBPage.js和pageCss.css实现分页,tab之间的切换未放在代码里面。
script type="text/javascript" src="<%=Epoint.EduFront.Bizlogic.CommFun.GetCommonRecourceDirectory()%>/Scripts/DBPage.js"></script> <link href="<%=Epoint.EduFront.Bizlogic.CommFun.GetCommonRecourceDirectory()%>/Style/Common/Theme1/css/pageCss.css" rel="stylesheet" /> <script type="text/javascript"> //用户ID var UserGuid = "<%=UserGuid%>"; //是否外部访问,如果外部访问则只显示申请通过的荣誉(我的荣誉) var ViewType = "<%=ViewType%>"; var Ajaxurl = Common.GlobalSettings.VirtualDirectory + "/ashx/Honor.ashx"; //获取我的各类型荣誉数量 function getHonorCount(type) { jQuery.ajax({ url: Ajaxurl, type: "post", //获取我的荣誉总数量 //data: { 'control': 'posts', 'op': 'count', 'posttype': 'personal', 'categoryguid': categoryguid, 'id': UserGuid, 'codevalue': PostCodeValue }, data: { 'control': 'honorcount', 'type': type, "userid": UserGuid }, dataType: "text", success: function (data) { if (data != "0") { //数量大于零,显示对应列表 if (type == '01') { //01为审核中 getHonorList(1, data, 5, "HonorApplyingListBox", "true", "pager2", type, UserGuid); } else if (type == '02') { //审核通过 getHonorList(1, data, 5, "HonorListBoxListBox", "true", "pager1", type, UserGuid); } else if (type == '03') { //审核未通过 getHonorList(1, data, 5, "HonorRefusedListBox", "true", "pager3", type, UserGuid); } } else { if (type == '03') { $("#HonorListBoxListBox").html("<div style='text-align:center;'>暂无数据~<div>"); } else if (type == '01') { $("#HonorApplyingListBox").html("<div style='text-align:center;'>暂无数据~<div>"); } else if (type == '02') { $("#HonorRefusedListBox").html("<div style='text-align:center;'>暂无数据~<div>"); } } }, error: function (XMLHttpRequest, txtStatus, errorThrown) { Common.ErrorHandle(XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + txtStatus + "|" + errorThrown); Common.ErrorHandle("HonorApplyList.ascx"); } }); } //根据用户guid,和type获取荣誉列表 function getHonorList(PageIndex, total, spanInterval, contentid, allowpagging, pagerId, type, userguid) { jQuery.ajax({ url: Ajaxurl, type: "post", //获取我的荣誉列表 data: { 'control': 'honorList', 'type': type, 'userid': userguid, 'PageIndex': PageIndex, 'spanInterval': spanInterval }, dataType: "json", success: function (jdata) { if (jdata.status == "success") { //创建荣誉列表 createHonorList(type, jdata.data, contentid); if (allowpagging == "true") { //是否允许分页 Paging(PageIndex, total, spanInterval, pagerId); } } }, error: function (XMLHttpRequest, txtStatus, errorThrown) { Common.ErrorHandle(XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + txtStatus + "|" + errorThrown); Common.ErrorHandle("HonorApplyList.ascx"); } }); } //根据荣誉数据,创建荣誉Html文本 function createHonorList(type, data, contentid) { //alert(data); var id = "#" + contentid; $(id).html(""); var table = "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr style='font-size: 14px; font-weight: bold;color:#CA7733'><td height='26' class='list'>荣誉称号</td><td width='150' align='center'>荣誉等级</td><td width='150' align='center'>授予部门</td><td width='150' align='center'>获得时间</td></tr>"; for (var i = 0; i < data.length; i++) { var s = "<tr>"; s += "<td height='26' class='list'>" + data[i].HonorTitle + "</td>"; s += "<td width='150' align='center'>" + data[i].HonorLevel + "</td>"; s += "<td width='150' align='center'>" + data[i].grantdepartment + "</td>"; s += "<td width='150' align='center' class='line4'>" + data[i].granttime + "</td>"; s += "</tr>"; table += s; } if (data.length > 0) { table += "</table>"; $(id).append(table); } else { $(id).html("暂无数据~"); } } //页面初始化 $(function () { if (ViewType == "inter") { //如果是本人 getHonorCount("01"); getHonorCount("02"); getHonorCount("03"); } else { $("#menu_2_1").html("荣誉"); $("#menu_2_2").hide(); $("#menu_2_3").hide(); $("#Honorapply").remove(); getHonorCount("02"); //个人公开文章分页 //如果是教师、则查询特定分类的文章 } }), //点击事件,根据不同身份,不同访问方式获取文章列表 //韦田野 2016-3-11修改 PageClick = function (pageIndex, total, spanInterval, pagerId) { if (pagerId == "pager1") { getHonorList(pageIndex, total, spanInterval, "HonorListBoxListBox", "true", pagerId, "02", UserGuid); } else if (pagerId == "pager2") { getHonorList(pageIndex, total, spanInterval, "HonorApplyingListBox", "true", pagerId, "01", UserGuid); } else if (pagerId == "pager3") { getHonorList(pageIndex, total, spanInterval, "HonorRefusedListBox", "true", pagerId, "03", UserGuid); } } </script> <div class="three"> <div class="head"> <div class="menub1_1" style="width: auto; font-size: 18px; margin-right: 15px;" id="menu_2_1" onmouseover="showtabs(2,1,3);">我的荣誉</div> <div class="menub1_2" style="width: auto; font-size: 18px; margin-right: 15px;" id="menu_2_2" onmouseover="showtabs(2,2,3);">审核中的荣誉</div> <div class="menub1_2" style="width: auto; font-size: 18px; margin-right: 15px;" id="menu_2_3" onmouseover="showtabs(2,3,3);">审核未通过</div> <div style="float: right; font-size: 18px; margin-top: 15px;" id="Honorapply"> <a id="LinkHonorPublish" class="publishbtn" runat="server" href='' target="_blank">荣誉申请</a> </div> </div> <div class="content" style="min-height: 410px;"> <div class="menugtab" id="menutab_2_1"> <div id="HonorListBoxListBox" style="min-height: 380px;"> </div> <div class="yahoo2" id="pager1" ></div> </div> <div class="menugtab" id="menutab_2_2" style="display: none;"> <div id="HonorApplyingListBox" style="min-height: 380px;"> </div> <div class="yahoo2" id="pager2"></div> </div> <div class="menugtab" id="menutab_2_3" style="display: none;"> <div id="HonorRefusedListBox" style="min-height: 380px;"> </div> <div class="yahoo2" id="pager3"></div> </div> </div> </div>
3:引用的DBpage.js和PageCss.css代码如下
DIV.yahoo2 { padding: 3px; MARGIN: 15px 3px 30px 3px; font-family: 'Microsoft YaHei'; TEXT-ALIGN: center; } DIV.yahoo2 A { border: 1px solid #dedede; font-family: 'Microsoft YaHei'; font-size: 14px; cursor: pointer; margin: 0 2px; color: black; padding: 3px 13px; } DIV.yahoo2 A:hover { background-color: #999999; border: solid 1px #999999; color: #FFFFFF; } DIV.yahoo2 A:active { border: 1px solid #dedede; font-weight: bold; margin:0 2px; } DIV.yahoo2 SPAN.current { FONT-WEIGHT: bold; COLOR: red; margin:0 2px; PADDING: 3px 13px; font-family: 'Microsoft YaHei'; font-size: 14px; } DIV.yahoo2 SPAN.disabled { border: 1px solid #dedede; font-family: 'Microsoft YaHei'; font-size: 14px; /*font-weight: bold;*/ cursor: pointer; width: 36px; margin-left: 2px; margin-right: 2px; color: gray; padding: 3px 13px; } DIV.yahoo2 A.next { BORDER-RIGHT: #ccdbe4 2px solid; BORDER-TOP: #ccdbe4 2px solid; MARGIN: 0px 0px 0px 10px; BORDER-LEFT: #ccdbe4 2px solid; BORDER-BOTTOM: #ccdbe4 2px solid; } DIV.yahoo2 A.next:hover { BORDER-RIGHT: #2b55af 2px solid; BORDER-TOP: #2b55af 2px solid; BORDER-LEFT: #2b55af 2px solid; BORDER-BOTTOM: #2b55af 2px solid; } DIV.yahoo2 A.prev { BORDER-RIGHT: #ccdbe4 2px solid; BORDER-TOP: #ccdbe4 2px solid; MARGIN: 0px 10px 0px 0px; BORDER-LEFT: #ccdbe4 2px solid; BORDER-BOTTOM: #ccdbe4 2px solid; } DIV.yahoo2 A.prev:hover { BORDER-RIGHT: #2b55af 2px solid; BORDER-TOP: #2b55af 2px solid; BORDER-LEFT: #2b55af 2px solid; BORDER-BOTTOM: #2b55af 2px solid; } DIV.yahoo2 .jump_input { border: solid 0px #dfdfdf; background-color: #ffffff; /*border-bottom:solid 1px #dfdfdf*/ } .jump_input:focus {outline: none;} DIV.yahoo2 .jump_a { border: 1px solid #dedede; font-family: 'Microsoft YaHei'; font-size: 14px; font-weight: bold; cursor: pointer; width: 36px; margin-left: 2px; margin-right: 2px; color: black; padding-left: 10px; padding-right: 10px; } DIV.yahoo2 .jump_a:hover { border: 1px solid #dedede; font-family: 'Microsoft YaHei'; font-size: 14px; font-weight: bold; cursor: pointer; width: 36px; margin-left: 2px; margin-right: 2px; color: black; padding-left: 10px; padding-right: 10px; background-color: white; }
function Paging(pageIndex, total, spanInterval, pagerId) { var pageS = total; if (pageS % spanInterval == 0) pageS = pageS / spanInterval; else pageS = parseInt(total / spanInterval) + 1; var $pager = $("#" + pagerId); var intPageIndex = parseInt(pageIndex); //清除分页div中的内容 //$("#" + pagerId + " span").remove(); //$("#" + pagerId + " a").remove(); $pager.children().remove(); //添加第一页 //if (intPageIndex == 1) // $pager.append("<span class='disabled'>第一页</span>"); //else { // var first = $("<a href='javascript:void(0)' first='" + 1 + "'>第一页</a>").click(function () { // PageClick($(this).attr('first'), total, spanInterval, pagerId,this); // return false; // }); // $pager.append(first); //} //添加上一页 if (intPageIndex == 1) $pager.append("<span class='disabled'>< 上页</span>"); else { var pre = $("<a href='javascript:void(0)' pre='" + (intPageIndex - 1) + "'>< 上页</a>").click(function () { PageClick($(this).attr('pre'), total, spanInterval, pagerId,this); return false; }); $pager.append(pre); } //设置分页的格式 这里可以根据需求完成自己想要的结果 var interval = 3; //设置间隔 var start = Math.max(1, intPageIndex - interval); //设置起始页 var end = Math.min(intPageIndex + interval, pageS)//设置末页 if (intPageIndex < interval + 1) { end = (2 * interval + 1) > pageS ? pageS : (2 * interval + 1); } if ((intPageIndex + interval) > pageS) { start = (pageS - 2 * interval) < 1 ? 1 : (pageS - 2 * interval); } var console = console || { log: function () { } }; console.log("pageIndex:" + pageIndex + " total:" + total + " spanInterval:" + spanInterval + " start:" + start + " end:" + end); //生成页码 for (var j = start; j < end + 1; j++) { if (j == intPageIndex) { var spanSelectd = $("<span class='current'>" + j + "</span>"); $pager.append(spanSelectd); } //if else { var a = $("<a href='javascript:void(0)'>" + j + "</a>").click(function () { PageClick($(this).text(), total, spanInterval, pagerId, this); return false; }); $pager.append(a); } //else } //for //上一页 if (intPageIndex == pageS) { $pager.append("<span class='disabled'>下页 ></span>"); } else { var next = $("<a href='javascript:void(0)' next='" + (intPageIndex + 1) + "'>下页 ></a>").click(function () { PageClick($(this).attr("next"), total, spanInterval, pagerId, this); return false; }); $pager.append(next); } //最后一页 //if (intPageIndex == pageS) { // $pager.append("<span class='disabled'>最后一页</span>"); //} //else { // var last = $("<a href='javascript:void(0)' last='" + pageS + "'>最后一页</a>").click(function () { // PageClick($(this).attr("last"), total, spanInterval, pagerId); // return false; // }); // $pager.append(last); //} //跳转功能 var jump = "<span>" + pageIndex + "/" + pageS + " 转到</span>" + "<a class='jump_a'><input class='jump_input' style='width: 40px;margin-top: -3px;' type='text'></input></a>"; $pager.append(jump); var btn_go = $("<a href='javascript:;'>GO</a>").click(function () { var $go=$("#" + pagerId + " .jump_input"); var goval = $go.val(); console.log(goval); if (isNaN(Number(goval)) || goval == "" || goval > pageS || goval < 1) { $go.val("1"); return; } console.log(goval); PageClick(goval, total, spanInterval, pagerId, this); return false; }); $pager.append(btn_go); }
4一般处理程序 ashx页面代码
public class Honor : IHttpHandler { private HttpRequest Request = HttpContext.Current.Request; public void ProcessRequest(HttpContext context) { Request = HttpContext.Current.Request; string control = Request["control"].ToLower(); string result = ""; try { switch (control) { case "honortitle"://荣誉称号 result = this.GetHonorTitle("称号"); break; case "rkxd"://任课学段 result = this.GetHonorTitle("任课学段"); break; case "rjxk"://任教学科 result = this.GetHonorTitle("学科分类"); break; case "honorlevel"://荣誉等级 result = this.getHonorLevelTree(); break; case "honorcount"://荣誉数量 { if (Request["userid"] != null && Request["userid"].ToString() != "") { //返回荣誉条数 result = GetHonorCount(Request["userid"].ToString(), Request["type"].ToString()); } break; } case "honorlist"://荣誉列表 { if (Request["userid"] != null && Request["userid"].ToString() != "") { //返回第N页对应类型荣誉数据 result = GetHonorList(Request["userid"].ToString(), Request["type"].ToString(), Request["PageIndex"].ToString(), Request["spanInterval"].ToString()); } break; } case "addhonor"://荣誉申请添加 { if (Request["userid"] != null && Request["userid"].ToString() != "") { //进行插入操作 result = AddHonor(Request["userid"].ToString(), Request["txtGrantDepartment"].ToString(), Request["txtHonorTime"].ToString(), Request["txtRJXK"].ToString(), Request["txtRKXD"].ToString(), Request["txtOtherHonorTitle"].ToString(), Request["txtHonorTitle"].ToString(), Request["HonorLevel"].ToString()); } break; } } } catch (Exception e) { result = this.GetResult("", e.Message); } context.Response.ContentType = "text/plain"; context.Response.Write(result); } /// <summary> /// 获取该用户对应类型的荣誉数量/// </summary> /// <param name="userguid"></param> /// <param name="honortype"></param> /// <returns></returns> public string GetHonorCount(string userguid, string honortype) { string sql = "select count(*) from honor where honorgainerguid = '" + userguid + "'and auditstate = '" + honortype + "'"; return Epoint.EduFront.Bizlogic.DB_Common.ExecuteToInt(sql).ToString(); } /// <summary> /// 获取分页荣誉称号列表/// </summary> /// <param name="userguid"></param> /// <param name="honortype"></param> /// <param name="pageIndex"></param> /// <param name="spanInterval"></param> /// <returns></returns> public string GetHonorList(string userguid, string honortype, string pageIndex, string spanInterval) { try { int pageStart = (Convert.ToInt32(pageIndex) - 1) * Convert.ToInt32(spanInterval); int pageEnd = Convert.ToInt32(pageIndex) * Convert.ToInt32(spanInterval); string sql = string.Format( "SELECT * FROM ( SELECT A.*, ROWNUM RN FROM (SELECT * FROM honor where honorgainerguid ='{0}' and auditstate ='{1}') A WHERE ROWNUM <= {2} ) WHERE RN > {3}", userguid, honortype, pageEnd, pageStart); DataView dv = Epoint.EduFront.Bizlogic.DB_Common.ExecuteToDataView(sql); StringBuilder sb = new StringBuilder(); sb.Append("["); foreach (DataRowView dr in dv) { StringBuilder sb_SinglePost = new StringBuilder(); sb_SinglePost.Append("{"); //如果有选择了荣誉称号,则显示荣誉称号、否则显示其他荣誉称号 if (dr["HonorTitle"] != null && Convert.ToString(dr["HonorTitle"]) != "") { sb_SinglePost.Append(string.Format("\"{0}\":\"{1}\",", "HonorTitle", GetCodetextByCodeValue("称号", dr["HonorTitle"].ToString()))); } else { sb_SinglePost.Append(string.Format("\"{0}\":\"{1}\",", "HonorTitle",dr["OtherHonorTitle"].ToString())); } sb_SinglePost.Append(string.Format("\"{0}\":\"{1}\",", "HonorLevel",GetCodetextByCodeValue("荣誉等级", dr["HonorLevel"].ToString()))); sb_SinglePost.Append(string.Format("\"{0}\":\"{1}\",", "grantdepartment", dr["grantdepartment"].ToString())); sb_SinglePost.Append(string.Format("\"{0}\":\"{1}\",", "granttime", dr["granttime"].ToString())); sb.Append(sb_SinglePost.ToString().TrimEnd(',') + "},"); } string result = sb.ToString().TrimEnd(',') + "]"; return this.GetResult(result, "success"); } catch (Exception e) { return "Error:" + e.Message; } } public string GetCodetextByCodeValue(string CodeName, string codevalue) { string sql = "select itemtext from code_items where codeid = (select codeid from code_main where codename ='" + CodeName + "') and itemvalue = '" + codevalue + "'"; return Epoint.EduFront.Bizlogic.DB_Common.ExecuteToString(sql); } /// <summary> /// 申请荣誉记录添加/// </summary> /// <param name="userid">用户guid</param> /// <param name="txtGrantDepartment">授予部门</param> /// <param name="txtHonorTime">授予时间</param> /// <param name="txtRJXK">任教学科</param> /// <param name="txtRKXD">任课学段</param> /// <param name="txtOtherHonorTitle">其他荣誉名称</param> /// <param name="txtHonorTitle">荣誉称号</param> /// <returns></returns> public string AddHonor(string userid, string txtGrantDepartment, string txtHonorTime, string txtRJXK, string txtRKXD, string txtOtherHonorTitle, string txtHonorTitle, string HonorLevel) { //根据用户UserGuid获取器所属学校信息 string Sql = "select XXGuid from jcxx_teacherinfo where rowGuid = '" + userid + "'"; try { string xxGuid = Epoint.EduFront.Bizlogic.DB_Common.ExecuteToString(Sql); string honoraddSql = string.Format("insert into honor(operatedate,RowGuid,HonorTitle,otherhonortitle,honorlevel,RKXD,RJXK,GrantTime,GrantDepartment,Honorgainername,honorgainerguid,xxguid,auditstate)values(to_date('{0}','yyyy-mm-dd hh24:mi:ss'),'{1}','{2}','{3}','{4}','{5}','{6}',to_date('{7}','yyyy-mm-dd hh24:mi:ss'),'{8}','{9}','{10}','{11}','{12}')", DateTime.Now, Guid.NewGuid(), txtHonorTitle, txtOtherHonorTitle, HonorLevel, txtRKXD, txtRJXK, Convert.ToDateTime(txtHonorTime), txtGrantDepartment, GetTeacherNameByGuid(userid), userid, xxGuid, "01"); Epoint.EduFront.Bizlogic.DB_Common.ExecuteNonQuery(honoraddSql); return "申请成功!"; } catch (Exception e) { return "Error:" + e.Message; } } /// <summary> /// 根据rowGuid查询用户姓名/// </summary> /// <param name="rowguid"></param> /// <returns></returns> public string GetTeacherNameByGuid(string rowguid) { string sql = "select XM from jcxx_teacherinfo where rowguid= '" + rowguid + "'"; return Epoint.EduFront.Bizlogic.DB_Common.ExecuteToString(sql); } /// <summary> /// 荣誉等级信息初始化(荣誉等级分为两级)/// </summary> /// <returns></returns> public string getHonorLevelTree() { string Sql = "select itemtext,itemvalue from code_items where codeid = (select codeid from code_main where codename ='荣誉等级') and itemvalue like '__'"; //string childlevel = "select itemtext,itemvalue from code_items where codeid = (select codeid from code_main where codename ='荣誉等级') and itemvalue like '__'"; StringBuilder sb = new StringBuilder(); sb.Append("["); DataView Firstlvdv = Epoint.EduFront.Bizlogic.DB_Common.ExecuteToDataView(Sql); StringBuilder parentsb = new StringBuilder(); foreach (DataRowView drv in Firstlvdv) { parentsb.Append("{"); parentsb.Append(string.Format("\"{0}\":\"{1}\",", "id", drv["itemvalue"])); parentsb.Append(string.Format("\"{0}\":\"{1}\",", "text", drv["itemtext"]));// "state":"closed", parentsb.Append(string.Format("\"{0}\":\"{1}\"", "state", "closed")); //父级默认节点关闭状态 string codevalue = drv["itemvalue"].ToString(); string childSql = "select itemtext,itemvalue from code_items where codeid = (select codeid from code_main where codename ='荣誉等级') and itemvalue like '" + codevalue + "__'"; DataView childdv = Epoint.EduFront.Bizlogic.DB_Common.ExecuteToDataView(childSql); StringBuilder childsb = new StringBuilder(); if (childdv.Count > 0) { childsb.Append(",\"children\":["); foreach (DataRowView childdrv in childdv) { childsb.Append("{"); childsb.Append(string.Format("\"{0}\":\"{1}\",", "id", childdrv["itemvalue"])); childsb.Append(string.Format("\"{0}\":\"{1}\"", "text", childdrv["itemtext"])); childsb.Append("},"); } parentsb.Append(childsb.ToString().TrimEnd(',') + "]"); } parentsb.Append("},"); } sb.Append(parentsb.ToString().TrimEnd(',') + "]"); return this.GetResult(sb.ToString(), "success"); } /// <summary> /// 获取荣誉代码项,返回Json串/// </summary> /// <returns></returns> public string GetHonorTitle(string codemainname) { string Sql = "select ItemValue,itemText from code_items where codeid =(select codeid from Code_Main where codename='" + codemainname + "') order by ItemValue asc"; DataView HTdv = Epoint.EduFront.Bizlogic.DB_Common.ExecuteToDataView(Sql); StringBuilder sb = new StringBuilder(); sb.Append("["); foreach (DataRowView dr in HTdv) { StringBuilder sb_SinglePost = new StringBuilder(); sb_SinglePost.Append("{"); sb_SinglePost.Append(string.Format("\"{0}\":\"{1}\",", "ItemValue", dr["ItemValue"].ToString())); sb_SinglePost.Append(string.Format("\"{0}\":\"{1}\",", "ItemText", dr["ItemText"].ToString())); sb.Append(sb_SinglePost.ToString().TrimEnd(',') + "},"); } string result = sb.ToString().TrimEnd(',') + "]"; return this.GetResult(result, "success"); } #region 公共方法 private string GetResult(string data, string message) { if (data != "") { return "{\"data\":" + data + ",\"status\":\"" + message + "\"}"; } else { return "{\"status\":\"" + message + "\"}"; } } #endregion public bool IsReusable { get { return false; } } }