一个完整的Ajax查询及对查询结果实现分页的范例
2011-11-21 06:27
603 查看
分页是WEB应用开发中最常用的功能之一,大多数是在动态页面(如:jsp、asp、php)中完成。pageObj是本人针对JavaScript数组实现分页的一个通用的对象,使用简单,效果良好,功能比较完备,其原理与jsp分页原理相同,如对数据进行分组、每组多少页、每页多少条记录等等,只是编写代码更为复杂,但实用价值高。本篇将介绍一个Ajax查询及对查询结果实现分页的全部过程,示例是对一个分类表进行查询。
查询的基本方法是:
pvo.query("请求url",function(){/*实现用户代码*/});
分页的基本方法是:
1、创建分页对象,详细参考page.html文件
var p=new pageObj({uid:"pageTD",list:label_v,numPerPage:24,numPerOne:8,barType:2,f:function(){ alert(p.list.length+"|"+p.pageList.length);}});
2、显示分页
p.showPage();
一、效果图
这是点击查询按钮后生成的分页结果
这是连续点击两次下一组按钮、点击第25页按钮后的效果
二、数据库表定义
create table label(
label_id bigint primary key, /*通用分类表,主键*/
parent_id bigint default 0, /*父键*/
label varchar(64), /*标签*/
groupid varchar(32) /*类别*/
);
三、客户端网页page.html文件
四、服务器端文件
1、Servlet文件
2、数据库连接文件
五、JavaScript分页组件page.js
下一篇将介绍List<Map>类型数组在表单管理中的应用
查询的基本方法是:
pvo.query("请求url",function(){/*实现用户代码*/});
分页的基本方法是:
1、创建分页对象,详细参考page.html文件
var p=new pageObj({uid:"pageTD",list:label_v,numPerPage:24,numPerOne:8,barType:2,f:function(){ alert(p.list.length+"|"+p.pageList.length);}});
2、显示分页
p.showPage();
一、效果图
这是点击查询按钮后生成的分页结果
这是连续点击两次下一组按钮、点击第25页按钮后的效果
二、数据库表定义
create table label(
label_id bigint primary key, /*通用分类表,主键*/
parent_id bigint default 0, /*父键*/
label varchar(64), /*标签*/
groupid varchar(32) /*类别*/
);
三、客户端网页page.html文件
<!-- 一个完整的JavaWEB下的Ajax查询及分页的范例 客户端代码 胡开明 2011-11-21 --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>一个完整的Ajax查询及对查询结果实现分页的范例</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="res/js/pvo.js"></script> <script type="text/javascript" src="res/js/jbxx.jsp"></script> <script type="text/javascript" src="res/js/page.js"></script> <script type="text/javascript"> function chaxun(){ var action=pvo.getRoot()+ "/ExServlet?method=queryLabel";//查询请求的action,如同form中的action; pvo.query(action, function(){ var p=new pageObj({//创建分页对象 uid:"browseTD",//指定一个容器,供显示结果 numPerPage:6,//每页显示的记录数 numPerOne:10,//每组的页数 list:pvo.RESULT,//这是查询结果 barType:2//2:表示在查询结果的上下方都显示索引条;0,只在查询结果的上方都显示索引条;1,只在查询结果的下方都显示索引条; }); p.f=function(){//实现用户方法 var list = p.pageList;//从分页的结果中取当前页的记录 var uid=p.bodyid; document.getElementById(uid).innerHTML=""; var header=""; var html=""; var keys=null; if(list.length>0){ for(var a=0;a<list.length;a++){//遍历当前分页的记录 html=html+"<tr>"; var m=list[a]; keys=m.keys(); for(var b=0;b<keys.length;b++){ var v=m.get(keys[b]);//提取字段值 if(v==null||v=="")v=" "; html=html+"<td>"+v+"</td>"; } html=html+"</tr>"; } }else{ html="<tr><td>暂无记录</td></tr>"; } if(keys!=null){ header="<tr>"; for(var b=0;b<keys.length;b++){ header=header+"<th align=center>"+keys[b]+"</th>";//用字段名构成列表的标题 } header=header+"</tr>"; } document.getElementById(uid).innerHTML="<table id='browseTable' border='1px' style='width:100%;'>"+header+html+"</table>"; } p.showPage();//显示分页结果 }); } </script> </head> <body> <p>一个完整的Ajax查询及对查询结果实现分页的范例</p> <p><input type="button" value="查询" onclick="chaxun()" /></p> <div id="browseTD" style="width:740px;"> </div> </body> </html>
四、服务器端文件
1、Servlet文件
/* * 一个完整的JavaWEB下的Ajax查询及分页的范例 * 服务端代码 * 2011-11-21 */ package cn.hkm.example; import cn.hkm.sql.ProcessVO; import cn.hkm.web.ProcessForm; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author 胡开明 */ @WebServlet(name = "ExServlet", urlPatterns = {"/ExServlet"}) public class ExServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String method = request.getParameter("method"); System.out.println(method); if ("queryLabel".equals(method)) { queryLabel(request, response); } } /** * @param request servlet request * @param response servlet response */ private void queryLabel(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/xml;charset=UTF-8"); String returnValue = ""; PrintWriter out = null; try { out = response.getWriter(); String sql = "select * from label"; ProcessVO pvo = new ProcessVO(_Con.getCon()); try { List v = pvo.getSomeRecord(sql); if (v.size() > 0) { for (int i = 0; i < v.size(); i++) { Map map = (Map) v.get(i); returnValue = returnValue + "<record>" + mapToXml(map) + "</record>"; } returnValue = "<records>" + returnValue + "</records>"; } else { returnValue = "<records></records>"; } } catch (SQLException ex) { ex.printStackTrace(); } finally { pvo.closeCon(); out.write(returnValue); out.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } public String mapToXml(Map m) { String xml = ""; if (m != null && m.size() > 0) { Set set = m.keySet(); Object[] obj = set.toArray(); for (int i = 0; i < obj.length; i++) { xml = xml + "<" + obj[i] + ">" + filterChar(m.get(obj[i])) + "</" + obj[i] + ">"; } } return xml; } /** * 在String中,使用s.replace("<","<");使用s.replace(">",">");不能达到预期效果 *替换字符'<'和'>' **/ public String filterChar(Object obj) { String str = ""; if (obj == null) { return str; } str = obj.toString(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != '<' && str.charAt(i) != '>' && str.charAt(i) != '"' && str.charAt(i) != '&') {// && str.charAt(i) != '\'' sb.append(str.charAt(i)); } else { if (str.charAt(i) == '<') { sb.append("<"); } if (str.charAt(i) == '>') { sb.append(">"); } if (str.charAt(i) == '"') { sb.append("""); } //if (str.charAt(i) == '\'') { // sb.append("’");//´ //} if (str.charAt(i) == '&') { sb.append("&"); } } } return sb.toString(); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
2、数据库连接文件
package cn.hkm.example; import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class _Con { public static synchronized Connection getCon() { Connection con = null; String url = "jdbc:microsoft:sqlserver://localhost:1433; SendStringParametersAsUnicode=false"; String userName = "admin"; String password = "admin";//pio99 try { Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); con = DriverManager.getConnection(url, userName, password); } catch (SQLException ex1) { ex1.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } return con; } }
五、JavaScript分页组件page.js
/** * 对数组分页 * 胡开明 * 范例: var p=new pageObj({uid:"pageTD",list:label_v,numPerPage:24,numPerOne:8,barType:2,f:function(){ alert(p.list.length+"|"+p.pageList.length);}}); p.showPage(); * @param config={node:null,uid:"",list:null,f:function(){}}; */ function pageObj(config){ var obj=this; if(config==null)config={}; var props={ node:null, uid:null,//容器id barid:"pageBar", barid2:"pageBar2", bodyid:"pageBody", list:null,//记录的结果集,如查询结果 pageList:null,//当前分页的子集,可供在用户方法中调用 numPerPage:24,//每页的记录的个数 numPerOne:8,//每组的页的个数 numGroup:0, index:0, withAnchor:false,//是否使用锚,以便定位到锚的位置 anchor:"", barType:0,//0:bar的位置只在顶部显示,1:bar的位置只在底部显示,2:bar的位置在顶部和底部都显示。 barClass:"pageBar",//通常给一个背景图即可 bodyClass:"pageContent",// f:null//用户方法 } for(var i in props)this[i]=(typeof config[i]=='undefined')?props[i]:config[i]; if(obj.f==null){ obj.f=function(){ alert('请定义用户方法。列:var p=new pageObj({uid:"pageTD",list:label_v,f:function(){ alert(p.list.length+"|"+p.pageList.length);}}); p.showPage();'); } } //if(obj.list==null)obj.list=pvo.getResult(); if(obj.list==null)obj.list=new Array(); if(obj.list!=null)obj.pageList=obj.list.slice(obj.numPerPage*obj.index,obj.numPerPage*obj.index+obj.numPerPage);//供用户当前使用的数据 if(obj.uid!=null){ obj.barid=obj.uid+"Bar"; obj.barid2=obj.uid+"Bar2"; obj.bodyid=obj.uid+"Body"; obj.anchor=obj.uid+"Anchor"; } var anchor=""; if(obj.withAnchor){ anchor="<div style='clear:both;height:0px;'><a name='"+obj.anchor+"'></a></div>" } //容器 开始 var listDiv=anchor+"<div><div id='"+obj.barid+"' style='float:left;margin: 0px auto;width:100%;height: 26px;line-height: 26px;background-color:#F0F0EE;color:#000000;text-align: left;font-family: Arial,Helvetica,sans-serif;font-size: 14px;display:none;' class="+obj.barClass+"></div><div id='"+obj.bodyid+"' style='float:left;margin: 0px auto;width:100%;' class="+obj.bodyClass+"></div></div>"; if(obj.barType==1){ listDiv=anchor+"<div><div id='"+obj.bodyid+"' style='float:left;margin: 0px auto;width:100%;' class="+obj.bodyClass+"></div><div id='"+obj.barid+"' style='float:left;margin: 0px auto;width:100%;height: 26px;line-height: 26px;background-color:#F0F0EE;color:#000000;text-align: left;font-family: Arial,Helvetica,sans-serif;font-size: 14px;display:none;' class="+obj.barClass+"></div></div>"; } if(obj.barType==2){ listDiv=anchor+"<div><div id='"+obj.barid+"' style='float:left;margin: 0px auto;width:100%;height: 26px;line-height: 26px;background-color:#F0F0EE;color:#000000;text-align: left;font-family: Arial,Helvetica,sans-serif;font-size: 14px;display:none;' class="+obj.barClass+"></div><div id='"+obj.bodyid+"' style='float:left;margin: 0px auto;width:100%;' class="+obj.bodyClass+"></div><div id='"+obj.barid2+"' style='float:left;margin: 0px auto;width:100%;height: 26px;line-height: 26px;background-color:#F0F0EE;color:#000000;text-align: left;font-family: Arial,Helvetica,sans-serif;font-size: 14px;display:none;' class="+obj.barClass+"></div></div>"; } function initDiv(){//写容器//分页页面结构 if(obj.node==null){ if(document.getElementById(obj.uid))obj.node=document.getElementById(obj.uid); } if(obj.node!=null)obj.node.innerHTML=listDiv; if(obj.list.length<=obj.numPerPage){ document.getElementById(obj.barid).style.display="none"; if(obj.barType==2){ document.getElementById(obj.barid2).style.display="none"; } }else{ document.getElementById(obj.barid).style.display="block"; if(obj.barType==2){ document.getElementById(obj.barid2).style.display="block"; } } } initDiv(); //容器 结束 //初始化索引条 开始 var all=obj.list.length; var allPages=0;//总页数 i=all%obj.numPerPage; if(i==0){ allPages=parseInt(all/obj.numPerPage); }else{ allPages=parseInt(all/obj.numPerPage+1); } var group=1;//总分组数 var j=all%(obj.numPerPage*obj.numPerOne); if(j==0){ group=parseInt(all/(obj.numPerPage*obj.numPerOne)); }else{ group=parseInt(all/(obj.numPerPage*obj.numPerOne)+1); } var oneGroupPages=obj.numPerOne;//当前组的页面数, if(allPages<obj.numPerOne){ oneGroupPages=allPages; } obj.showGroup=function(numGroup){ obj.numGroup=numGroup; obj.index=numGroup*obj.numPerOne; obj.showPage(obj.index); } obj.showPage=function(index){ if(obj.list.length==0){ return; } if(index==null)index=0; obj.index=index; if(allPages-obj.numGroup*obj.numPerOne<obj.numPerOne)oneGroupPages=allPages-obj.numGroup*obj.numPerOne; else{ oneGroupPages=obj.numPerOne; } obj.pageList=obj.list.slice(obj.numPerPage*obj.index,obj.numPerPage*obj.index+obj.numPerPage); if(obj.list.length<=obj.numPerPage){//不显示索引条 obj.pageList=obj.list; } var begin=obj.numGroup*obj.numPerOne; var end=obj.numGroup*obj.numPerOne+oneGroupPages; var visit=""; var visit2=""; if(obj.withAnchor){ for(i=begin;i<end;i++){ visit=visit+"<span id='"+obj.uid+"_page_"+i+"' style='float:left;margin-top:6px;margin-left:1px;padding:1px 6px 1px 6px;width:auto;line-height:14px;height:14px;text-indent:0px;text-align:center;font-family:Helvetica,Arial,sans-serif;font-size: 12px;font-weight:bold;background:#7B7B63;color:#ffffff;cursor:pointer;'><a style='color:#ffffff;' href='#"+obj.anchor+"'>"+(i+1)+"</a></span>"; visit2=visit2+"<span id='"+obj.uid+"_pageB_"+i+"' style='float:left;margin-top:6px;margin-left:1px;padding:1px 6px 1px 6px;width:auto;line-height:14px;height:14px;text-indent:0px;text-align:center;font-family:Helvetica,Arial,sans-serif;font-size: 12px;font-weight:bold;background:#7B7B63;color:#ffffff;cursor:pointer;'><a style='color:#ffffff;' href='#"+obj.anchor+"'>"+(i+1)+"</a></span>"; } }else{ for(i=begin;i<end;i++){ visit=visit+"<span id='"+obj.uid+"_page_"+i+"' style='float:left;margin-top:6px;margin-left:1px;padding:1px 6px 1px 6px;width:auto;line-height:14px;height:14px;text-indent:0px;text-align:center;font-family:Helvetica,Arial,sans-serif;font-size: 12px;font-weight:bold;background:#7B7B63;color:#ffffff;cursor:pointer;'>"+(i+1)+"</span>"; visit2=visit2+"<span id='"+obj.uid+"_pageB_"+i+"' style='float:left;margin-top:6px;margin-left:1px;padding:1px 6px 1px 6px;width:auto;line-height:14px;height:14px;text-indent:0px;text-align:center;font-family:Helvetica,Arial,sans-serif;font-size: 12px;font-weight:bold;background:#7B7B63;color:#ffffff;cursor:pointer;'>"+(i+1)+"</span>"; } } var next="<span id='"+obj.uid+"_next' style='float:left;margin-top:6px;margin-left:1px;padding:1px 1px 1px 1px;line-height:14px;height:14px;background:#7B7B7B;color:#efefef;cursor:pointer;' title='下一组'><div style='width:20px;height:14px;'>>></div></span>"; var next2="<span id='"+obj.uid+"_next2' style='float:left;margin-top:6px;margin-left:1px;padding:1px 1px 1px 1px;line-height:14px;height:14px;background:#7B7B7B;color:#efefef;cursor:pointer;' title='下一组'><div style='width:20px;height:14px;'>>></div></span>"; var pre="<span id='"+obj.uid+"_pre' style='float:left;margin-top:6px;margin-left:1px;padding:1px 1px 1px 1px;line-height:14px;height:14px;background:#7B7B7B;color:#efefef;cursor:pointer;' title='上一组'><div style='width:20px;height:14px;'><<</div></span>"; var pre2="<span id='"+obj.uid+"_pre2' style='float:left;margin-top:6px;margin-left:1px;padding:1px 1px 1px 1px;line-height:14px;height:14px;background:#7B7B7B;color:#efefef;cursor:pointer;' title='上一组'><div style='width:20px;height:14px;'><<</div></span>"; var s=""; var s2=""; if(group>1){//按多组方式显示索引 s="<div style='float:left;margin: 0px auto;width:100%;'><span style='float:left;margin-top:6px;margin-left:1px;padding:1px 6px 1px 6px;line-height:14px;height:14px;text-indent:0px;'>" + all + "条/" + allPages + "页</span>"+pre+ next+" "+visit +"</div>"; s2="<div style='float:left;margin: 0px auto;width:100%;'><span style='float:left;margin-top:6px;margin-left:1px;padding:1px 6px 1px 6px;line-height:14px;height:14px;text-indent:0px;'>" + all + "条/" + allPages + "页</span>"+pre2+ next2+" "+visit2 +"</div>"; }else{//按一组方式显示索引 s="<div style='float:left;margin: 0px auto;width:100%;'><span style='float:left;margin-top:6px;margin-left:1px;padding:1px 6px 1px 6px;line-height:14px;height:14px;text-indent:0px;'>" + all + "条/" + allPages + "页</span>"+" "+visit+"</div>"; s2="<div style='float:left;margin: 0px auto;width:100%;'><span style='float:left;margin-top:6px;margin-left:1px;padding:1px 6px 1px 6px;line-height:14px;height:14px;text-indent:0px;'>" + all + "条/" + allPages + "页</span>"+" "+visit2+"</div>"; } document.getElementById(obj.barid).innerHTML=s; document.getElementById(obj.uid+"_page_"+index).style.backgroundColor="#990000"; if(obj.barType==2){ document.getElementById(obj.barid2).innerHTML=s2; document.getElementById(obj.uid+"_pageB_"+index).style.backgroundColor="#990000"; } for(i=begin;i<end;i++){ document.getElementById(obj.uid+"_page_"+i).onclick=function(){ var x=this.id; x=x.substring((obj.uid+"_page_").length);//x=x.replace(/[a-zA-Z_]|\s+/g, ""); x=parseInt(x); obj.showPage(x); } if(obj.barType==2){ document.getElementById(obj.uid+"_pageB_"+i).onclick=function(){ var x2=this.id; x2=x2.substring((obj.uid+"_pageB_").length);//x2=x2.replace(/[a-zA-Z_]|\s+/g, ""); x2=parseInt(x2); obj.showPage(x2); } } } if(obj.numGroup<(group-1)){ if(document.getElementById(obj.uid+"_next")){ document.getElementById(obj.uid+"_next").onclick=function(){ obj.showGroup(obj.numGroup+1); } } if(obj.barType==2){ if(document.getElementById(obj.uid+"_next2")){ document.getElementById(obj.uid+"_next2").onclick=function(){ obj.showGroup(obj.numGroup+1); } } } }else{ if(document.getElementById(obj.uid+"_next")){ document.getElementById(obj.uid+"_next").onclick=function(){ obj.showGroup(group-1); } } if(obj.barType==2){ if(document.getElementById(obj.uid+"_next2")){ document.getElementById(obj.uid+"_next2").onclick=function(){ obj.showGroup(group-1); } } } } if(obj.numGroup>0){ if(document.getElementById(obj.uid+"_pre")){ document.getElementById(obj.uid+"_pre").onclick=function(){ obj.showGroup(obj.numGroup-1); } } if(obj.barType==2){ if(document.getElementById(obj.uid+"_pre2")){ document.getElementById(obj.uid+"_pre2").onclick=function(){ obj.showGroup(obj.numGroup-1); } } } }else{ if(document.getElementById(obj.uid+"_pre")){ document.getElementById(obj.uid+"_pre").onclick=function(){ obj.showGroup(0); } } if(obj.barType==2){ if(document.getElementById(obj.uid+"_pre2")){ document.getElementById(obj.uid+"_pre2").onclick=function(){ obj.showGroup(0); } } } } obj.f(); } }
下一篇将介绍List<Map>类型数组在表单管理中的应用
相关文章推荐
- 利用MySQL的一个特性实现MySQL查询结果的分页显示
- 利用MySQL的一个特性实现MySQL查询结果的分页显示
- 使用ajax、pageHelpler分页插件、利用json数据特性实现分页查询
- jQuery实现的分页功能,包括ajax请求,后台数据,有完整demo
- 使用Hibernate criteria进行分页查询时,如何实现一次查询取得总记录数和分页后结果集
- 一个分页排序SQL查询结果集不确定的案例
- SSI框架---实现查询结果分页显示
- 使用jggrid时与具体ORM实现无关的分页参数及查询结果封装.
- iOS程序员利用分页和模糊查询技术实现一个App接口
- 利用JQuery方便实现基于Ajax的数据查询、排序和分页功能
- springmvc + jquery datatable + ajax实现服务端动态分页查询
- 反射技术将查询结果封装为对象_编写一个基本的连接池来实现连接的复用
- ajax实现分页和分页查询
- Ajax技术之与服务器通信-一个完整的实例(实现检测用户名是否唯一功能)
- ORACLE之储存过程实现查询结果分页显示
- springmvc + jquery datatable + ajax实现服务端动态分页查询
- 一个分页排序SQL查询结果集不确定的案例
- 实现ASPxGridView基于AJAX和自定义数据源的分页查询
- jQuery实现分页功能(含ajax请求、后台数据、附完整demo)