jquery-ajax高效分页(mysql版)

本文是struts2+jquery-ajax实现的在mySQL下的高效分页
1:先看下预览效果:(30多万数据测试)
  jquery-ajax高效分页(mysql版)_第1张图片

2:这个实现首先把后台数据库返回的RowSet转化成json格式的字符串,再把这个json格式的字符串传给前台,用jquery解析
  RowSet数据到json格式的数据转化函数如下:
 
/*
      * @param count 数据总条目数
      * @param pageCount 每页显示数据数
      * */
     private static String RowSetToJson(RowSet rt,int count,int pageCount){
    	 ResultSetMetaData rm=null;
    	 StringBuilder sb=new StringBuilder();
    	 try {
			 rm=rt.getMetaData();
			 sb.append("{\"pageCount\":\""+count+"\",\"pageData\":[");
			 int columNum=rm.getColumnCount();
			 List<String> list=new ArrayList<String>();
			 for(int i=0;i<columNum;i++){
				 list.add(rm.getColumnName(i+1));
			 }
			 
			 for(int i=0;i<pageCount&&rt.next();i++){
				 sb.append("{");
				 for(int j=0;j<list.size();j++){
					 if(j!=list.size()-1){
						 sb.append("\""+list.get(j)+"\":\""+rt.getString(list.get(j))+"\",");
					 }else{
						 sb.append("\""+list.get(j)+"\":\""+rt.getString(list.get(j))+"\"");
					 }
				 }
				 if(i!=pageCount-1){
					 sb.append("},");
				 }else{
					 sb.append("}");
				 } 
			 }
			 sb.append("]}");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	 return sb.toString();
     }

  调用转化函数方法:
 
 public static String getJson(String tableName,String select,String where,String orderby,int pageIndex,int pageCount){
         StringBuilder sb=new StringBuilder();
         sb.append("select "+select+" from "+tableName);
         if(!"".equals(where)){
        	 sb.append(" ");
        	 if(where.startsWith("where")){
        		 sb.append(" "+where);
        	 }else{
        		 sb.append(" where "+where);
        	 }
         }
         sb.append(" "+orderby+" ");
         int temp=(pageIndex-1)*pageCount;
         sb.append(" limit "+temp+","+pageCount);
    	 RowSet rt=DBop.search(sb.toString());
    	 //求数据总条目数
         int rowNum=0;
         rowNum=DBop.getNum(tableName,where);
    	 return RowSetToJson(rt,rowNum,pageCount);
     }


3:在action函数里调用方法:
  
import com.jiang.DB.GetData;
import com.opensymphony.xwork2.ActionSupport;

public class GetPageData extends ActionSupport {
	private String p;//当前页
	private String orderby;//排序规则
	private String data;
     public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public String getP() {
		return p;
	}

	public void setP(String p) {
		this.p = p;
	}

	public String getOrderby() {
		return orderby;
	}

	public void setOrderby(String orderby) {
		this.orderby = orderby;
	}

	public String execute()throws Exception{
    	 if("".equals(orderby)){
    		 orderby="order by id_t";
    	 }
    	 if("".equals(p)){
    		 p=String.valueOf(1);
    	 }
    	 if(Integer.parseInt(p)==0){
    		 p=String.valueOf(1);
    	 }
    	 data=GetData.getJson("pagetest", "*", "","order by id_t", Integer.parseInt(p), 10);
//    	 System.out.println(data);
    	 return SUCCESS;
     }
}
]

4:页面ajax请求代码:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>jquery-ajax分页</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
	<script src="js/jquery.js" type="text/javascript"></script>
	<script src="js/jquery.pagination.js" type="text/javascript"></script>
	<link href="js/pagination.css" rel="stylesheet" type="text/css" />
	<script type="text/javascript">
	   var orderby="order by id_t";
	   $(document).ready(function(){
		   initData(0);
		   });
       //翻页响应
	   function pageselectCallback(page_id,jq) {
           initData(page_id);
       }

	   function initData(pageindx)
       {
          var tbody="";
          var pageCount="";
         $.ajax({
              type: "POST",//用POST方式传输
              dataType:"json",//数据格式:JSON
              url:'getData.action',//目标地址
              async:false,//作用是防止在ajax成功调用之前就调用$("#Pagination").pagination,这个时候数据个数还没有初始化
              data:"p="+(pageindx+1)+"&orderby="+escape(orderby),
              beforeSend:function(){$("#divload").show();$("#Pagination").hide();},//发送数据之前
              complete:function(){$("#divload").hide();$("#Pagination").show();},//接收数据完毕
              success:function(json) {
                       $("#productTable tr:gt(0)").remove();
                       var productData = json.pageData;
                       pageCount=json.pageCount;
                       if(productData==""){
                          $("#divload").hide();
                          dis();
                          return false;
                       }
                       $.each(productData, function(i, n) {
                           var trs = "";
                           trs += "<tr><td align='center'>" + n.id_t + "</td><td align='center'>"+n.name_t+"</td><td align='center'>"+n.reamark_t+"</td><td align='center'>"+n.age_t+"</td><td align='center'>"+n.hobby_t+"</td><td align='center'><a href=\"javascript:edit('')\">编辑</a>&nbsp;&nbsp;<a href=\"javascript:view('')\">查看</a></td></tr>";
                        tbody+=trs; 
                       });

                         $("#productTable").append(tbody);
                        //行交替颜色
                         $("#productTable tr:gt(0):odd").attr("class", "");
                         $("#productTable tr:gt(0):even").attr("class", "");
                       }//end of success
               });
              if(pageCount!=0){
                  $("#Pagination").pagination(pageCount, {
                   callback: pageselectCallback,
                   prev_text: '<< 上一页',
                   next_text: '下一页 >>',
                   items_per_page:10,
		            num_display_entries:6,
		            current_page:pageindx,
		            num_edge_entries:2
               });
              }
      }
//排序
	   function Sort(ordercolumn,ordertipid){
       var ordertype="";//1:desc,0:asc
       var $orderimg = $("#"+ordertipid);
       if($orderimg.html()!="")
       {
            var imgsrc="";
            imgsrc = $("img",$orderimg).attr("src");
            if(imgsrc.indexOf("asc")>-1){
                 $(".ordertip").empty();
                 $orderimg.html("&nbsp;<img src=\"images/sort_desc.gif\" align=\"absmiddle\">");
           
                 ordertype = 1;
            }
           else
           { 
              $(".ordertip").empty();
               $orderimg.html("&nbsp;<img src=\"images/sort_asc.gif\" align=\"absmiddle\">");
              
               ordertype = 0;
           }
       }
       else
       {
            $(".ordertip").empty();
            $orderimg.html("&nbsp;<img src=\"images/sort_desc.gif\" align=\"absmiddle\">");
               ordertype = 1;
        }
       
       orderby = ordercolumn+"_"+ordertype;
       initData(0);
       
   }
	</script>
  </head>
  
  <body>
    <div id="divload" style="top:50%; right:50%;position:absolute; padding:0px; margin:0px; z-index:999"></div>
    <table id="productTable" style="width:70%" class="TableList">
           <tr class="TableHeader">
             <th nowrap align="middle"><a style="cursor:pointer;" onclick="Sort('id_t','id_t');return false;">id</a><span id="id_t" class="ordertip"><img src="images/sort_desc.gif" align="absmiddle"></span></th>
             <th nowrap align="middle"><a style="cursor:pointer;" onclick="Sort('name_t','name_t');return false;">name</a><span id="name_t" class="ordertip"><img src="images/sort_desc.gif" align="absmiddle"></span></th>
             <th nowrap align="middle"><a style="cursor:pointer;" onclick="Sort('remark_t','remark_t');return false;">remark</a><span id="remark_t" class="ordertip"><img src="images/sort_desc.gif" align="absmiddle"></span></th>
             <th nowrap align="middle"><a style="cursor:pointer;" onclick="Sort('age_t','age_t');return false;">age</a><span id="age_t" class="ordertip"><img src="images/sort_desc.gif" align="absmiddle"></span></th>
             <th nowrap align="middle"><a style="cursor:pointer;" onclick="Sort('hobby_t','hobby_t');return false;">hobby</a><span id="hobby_t" class="ordertip"><img src="images/sort_desc.gif" align="absmiddle"></span></th>
             <th nowrap align="middle"><a style="cursor:pointer;">操作</a><span id="Span8" class="ordertip"><img src="images/sort_desc.gif" align="absmiddle"></span></th>
          </tr>
     </table>
        <div id="Pagination" class="flickr" style="text-align:left"></div>
  </body>
</html>


5:struts.xml代码:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
  <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    
    <package name="default" namespace="/" extends="struts-default">
        <default-action-ref name="index" />
        <action name="getData" class="com.jiang.action.GetPageData">
            <result name="success">/pageData.jsp</result>
        </action>
    </package>
</struts>    


6:原代码下载:
  

你可能感兴趣的:(jquery,json,Ajax,mysql,struts)