`
gwh_08
  • 浏览: 331544 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

三种不同的分页方式

 
阅读更多

习惯了ext的Ext.grid.GridPanel与Ext.data.Store封装好了的分页方式以及

ajax处理方式

Ext.Ajax.request({
         	url: 'xxx.action',
			failure: function(form, action){
    			xxxx;
			},
			success: function(response, action){
				xxxx;
			}
		});
 

和对后台响应json的处理

Ext.Ajax.request({
         	url: 'xxx.action',
			failure: function(form, action){
    			   xxxx;
			},
			success : function(form, action) {
 		            var jsonData =  Ext.util.JSON.decode(action.response.responseText);
                          }
		});

 突然让手写jsp风格的分页,突然搓手不及了,可怜,两年没有手写过纯jsp页面了,回忆,查阅api终于按时交工,一方自己再次怠慢,先整理如下,以防再次出现窘迫的情况。

1.ext分页,略。

2.jquery插件jquery.pagination.js分页:

首先假设server端代码响应没问题,且返回形式为json:具体如下:

public void outJsonArray(Object array) {
		try {
		        HttpServletResponse res = ServletActionContext.getResponse();
		        res.setContentType("text/javascript;charset=UTF-8");
		        PrintWriter out = res.getWriter();
		        out.write(JSONArray.fromObject(array).toString());
	          } catch (IOException e) {
	          }
	}
public void jsonTest(){
		try {
			List<UserVO> list = userService.findAllUser();
			outJsonArray(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 

jsp代码如下:

<%@ page pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath}/js/pagination.css" />
<script type="text/javascript"
	src="${pageContext.request.contextPath}/js/jquery-1.7.1.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/js/jquery.pagination.js"></script>
        
<!-- Load data to paginate -->
<script type="text/javascript">
     // 当文档加载时,获取数据 initialize pagination and form 
     var jso = "";
     $(document).ready(function(){
		 getData();
     });
     //jqueryAjax调用后台action获取数据
    /*  jQuery.post(url,data,success(data, textStatus, jqXHR),dataType);
     	该函数是简写的 Ajax 函数,等价于:

     $.ajax({
       type: 'POST',
       url: url,
       data: data,
       success: success,
       dataType: dataType
     }); */
     function getData(){
    	 $.post("jsonTestUser.action",function(result){
    		 	jso = result;
    		 	initpag(jso);
    		    }, "json");
     }
    //初始化pagination插件 and form表单参数
    function initpag(jso){
	    // 根据form表单创建 pagination element
	    var optInit = getOptionsFromForm();
	    $("#Pagination").pagination(jso.length, optInit);
	         
		// Event Handler for for button
		$("#setoptions").click(function(){
		    var opt = getOptionsFromForm();
		    // Re-create pagination content with new parameters
		    $("#Pagination").pagination(jso.length, opt);
	    }); 
    }
     // This file demonstrates the different options of the pagination plugin
        // It also demonstrates how to use a JavaScript data structure to 
        // generate the paginated content and how to display more than one 
        // item per page with items_per_page.
                
        /**
         * Callback function that displays the content.
         *
         * Gets called every time the user clicks on a pagination link.
         *
         * @param {int}page_index New Page index
         * @param {jQuery} jq the container with the pagination links as a jQuery object
         */
		function pageselectCallback(page_index, jq){
            // Get number of elements per pagionation page from form
            var items_per_page = $('#items_per_page').val();
            var max_elem = Math.min((page_index+1) * items_per_page, jso.length);
            var newcontent = '';
            newcontent += '<table width=80% align="center" cellpadding=0 cellspacing="1" style="border:1px solid black">\r\n';
            newcontent += '<tr>';
        	newcontent +='<td colspan="4" ><div class="mytitle">用户列表</div></td>'; 
       		newcontent +=   '</tr>';
        	newcontent +=   '<tr class="pt9" height="30">';
        	newcontent +=   '<td><b>登陆名</b></td>';
        	newcontent +=   '<td><b>昵称</b></td>';
        	newcontent +=  '<td><b>性别</b></td> ';
        	newcontent +=   '<td><b>电子邮箱</b></td>';
        	newcontent += '</tr>';
            // Iterate through a selection of the content and build an HTML string
            for(var i=page_index*items_per_page;i<max_elem;i++){
            	var loginName = jso[i].loginName;
            	var userName  = jso[i].userName;
            	var userSex   = jso[i].userSex;
            	var userEmail = jso[i].userEmail;
            	newcontent += '<tr>';
            	newcontent += '<td>'+loginName+'</td>';
                newcontent += '<td>'+userName+'</td>';
                newcontent += '<td>'+userSex+'</td>';
                newcontent += '<td>'+userEmail+'</td>';
                newcontent += '</tr>';
            }
            newcontent += '</table>';
            // Replace old content with new content
            $('#Searchresult').html(newcontent);
            
            // Prevent click eventpropagation
            return false;
        }
     // The form contains fields for many pagiantion optiosn so you can 
        // quickly see the resuluts of the different options.
        // This function creates an option object for the pagination function.
        // This will be be unnecessary in your application where you just set
        // the options once.
        function getOptionsFromForm(){
            var opt = {callback: pageselectCallback};
            // Collect options from the text fields - the fields are named like their option counterparts
            $("input:text").each(function(){
                opt[this.name] = this.className.match(/numeric/) ? parseInt(this.value) : this.value;
            });
            // Avoid html injections in this demo
            var htmlspecialchars ={ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;"}
            $.each(htmlspecialchars, function(k,v){
                opt.prev_text = opt.prev_text.replace(k,v);
                opt.next_text = opt.next_text.replace(k,v);
            })
            return opt;
        }
        
    
		
        
        </script>
        <style type="text/css">
         <!--
        * {
            padding: 0;
            margin: 0;
        }
        body {
            background-color: #fff;
            margin: 20px;
            padding: 0;
            height: 100%;
            font-family: Arial, Helvetica, sans-serif;
        }
		
		h1 {
			margin-bottom:10px;
			font-size:1.5em;
		}
        
        h3 {
			margin-top:10px;
			font-size:1em;
		}
        
		#Searchresult {
			margin-top:15px;
			margin-bottom:15px;
			border:solid 1px #eef;
			padding:5px;
			background:#eef;
            width:40%;
		}
        
        #Searchresult dt {
            font-weight:bold;
        }
        
        #Searchresult dd {
            margin-left:25px;
        }
		
		#footer {
			margin-top:20px;
			font-size:60%;
			color:#15B;
		}
		
		label {
			float:left;
			width:250px;
			display:block;
		}
		
		form p {
			clear:both;
		}
		
        -->
        </style>
		
        <title>jQuery and jQuery Pagination Plugin and json Demo</title>
    </head>
    <body>
    	<h1>jQuery and jQuery Pagination Plugin and json Demo</h1>
        <div id="Pagination" class="pagination">
        </div>
		<br style="clear:both;" />
        <h3>List of former members of the United States House of Representatives (A)</h3>
		<dl id="Searchresult">
			<dt>Search Results will be inserted here ...</dt>
		</dl>
        <h3>Config form for pagination parameters</h3>
        <!-- This form is just to demonstrate the whole range of options and display styles. -->
		<form name="paginationoptions">
			<p><label for="items_per_page">Number of items per page</label><input type="text" value="5" name="items_per_page" id="items_per_page" class="numeric"/></p>
			<p><label for="num_display_entries">Number of pagination links shown</label><input type="text" value="10" name="num_display_entries" id="num_display_entries" class="numeric"/></p>
			<p><label for="num">Number of start and end points</label><input type="text" value="2" name="num_edge_entries" id="num_edge_entries" class="numeric"/></p>
			<p><label for="prev_text">"Previous" label</label><input type="text" value="Prev" name="prev_text" id="prev_text"/></p>
			<p><label for="next_text">"Next" label</label><input type="text" value="Next" name="next_text" id="next_text"/></p>
			<input type="button" id="setoptions" value="Set options" />
		</form>
    </body>
</html>

 3.ajax方式分页

首先假设server端代码响应没问题,且返回形式为json:具体如下:

public class Page<T> {
//公共变量
	public static final String ASC = "asc";
	public static final String DESC = "desc";

	public static final int MIN_PAGESIZE = 2;
	public static final int MAX_PAGESIZE = 200;

	//分页参数
	protected int pageNo = 1;
	protected int pageSize = MIN_PAGESIZE;
	protected String orderBy = null;
	protected String order = null;
	protected boolean autoCount = true;

	//返回结果
	protected List<T> result = Collections.emptyList();
	protected int totalCount = -1;
        //get,set方法;略
}
 
public class ListRange<T> {
	boolean success;
	String message;
	long totalCount;
	List<T> list;
        
       //get,set方法;略
 }
 
public void outJson(Object array) {
		try {
		        HttpServletResponse res = ServletActionContext.getResponse();
		        res.setContentType("text/javascript;charset=UTF-8");
		        PrintWriter out = res.getWriter();
		        out.write(JSONObject.fromObject(obj).toString());
	          } catch (IOException e) {
	          }
	}

 

 

public void ajaxTest() {
		LOG.info("in list method");
		ListRange<UserVO> listRange = new ListRange<UserVO>();
		try {//param获取页面传过来的参数
                       //start,sql查询语句开始查询起始值
                       //limit,sql查询个数;sort,sql查询排序对象;dir,sql查询顺序,desc或asc
                     
                        Page<UserVO> page = userService.findUserList(param);
			if (page != null) {
				listRange.setList(page.getResult());
				listRange.setTotalCount(page.getTotalCount());
				//保存开始页信息
				listRange.setMessage(start);
				listRange.setSuccess(true);
			}
		} catch (Exception e) {
			listRange.setSuccess(false);
			LOG.error("查询失败", e);
			e.printStackTrace();
		}
		
		outJson(listRange);
	}

 jsp页面代码如下:

<%@ page pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        
<!-- Load data to paginate -->
<script type="text/javascript">
var xmlhttp ;
//创建对象

function updataTable(method,url,start){
    if (window.XMLHttpRequest){
	     // code for IE7+, Firefox, Chrome, Opera, Safari
	     xmlhttp=new XMLHttpRequest();
   }
   else{
  	 // code for IE6, IE5
	     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
    var _url = url + "?start="+start+"&limit=2&sort=loginName&dir=desc";
    xmlhttp.onreadystatechange = callback1;
       xmlhttp.open("post",_url,true);
	    xmlhttp.send();
}


function winload(){
   updataTable("GET","ajaxTestUser.action",0);
}

 function callback1(){
    if(xmlhttp.readyState == 4){
          if(xmlhttp.status == 200){
           var json =  xmlhttp.responseText;
           //对json的处理,注意是eval('('+json+')');若为eval(json);会报错
	    	 var doc = eval('('+json+')');
            var currentPage = doc.message;
            var totalPage = doc.totalCount;//总数据条数
            var prePage = parseInt(currentPage) - 2;
            var nextPage = parseInt(currentPage) + 2;
            var innerHTML = "";
            if (parseInt(totalPage)>0) {
                innerHTML += "<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\">\r\n";
                innerHTML += '<tr>';
	        	innerHTML +='<td colspan="4" ><div class="mytitle">用户列表</div></td>'; 
	       		innerHTML +=   '</tr>';
	        	innerHTML +=   '<tr class="pt9" height="30">';
	        	innerHTML +=   '<td><b>登陆名</b></td>';
	        	innerHTML +=   '<td><b>昵称</b></td>';
	        	innerHTML +=  '<td><b>性别</b></td> ';
	        	innerHTML +=   '<td><b>电子邮箱</b></td>';
	        	innerHTML += '</tr>';
	        	for(var i=0;i<doc.list.length;i++){
	            	var loginName = doc.list[i].loginName;
	            	var userName  = doc.list[i].userName;
	            	var userSex   = doc.list[i].userSex;
	            	var userEmail = doc.list[i].userEmail;
	            	innerHTML += '<tr>';
	            	innerHTML += '<td>'+loginName+'</td>';
	                innerHTML += '<td>'+userName+'</td>';
	                innerHTML += '<td>'+userSex+'</td>';
	                innerHTML += '<td>'+userEmail+'</td>';
	                innerHTML += '</tr>';
	            }
	            innerHTML += '</table>\r\n';
            } else {
                innerHTML += "暂时没有任何用户";
            }   
            document.getElementById("newslist").innerHTML = innerHTML;
            document.getElementById("prePage").innerHTML = "<a href=\"javascript:void(0)\" onClick=\"goToStart('" + prePage + "')\">上一页</a>";
            document.getElementById("nextPage").innerHTML = "<a href=\"javascript:void(0)\" onClick=\"goToStart('" + nextPage + "')\">下一页</a>";

          } else{
              alert("返回状态有错"+xmlhttp.status);
          }
    }
 }
 
 
 //页面跳转
function goToStart(start) {

   updataTable("get","ajaxTestUser.action",start);	
}
</script>
		
        <title>Ajax Page DEMO</title>
    </head>
    <body>
    	<h1>Ajax Page Demo</h1>
       <table width="500" border="0" cellspacing="0" cellpadding="4">
			<tr>
				<td align="center">
    				<button onclick="winload()">打开窗口</button>
				</td>
			</tr>
		</table>
		<table width="500" border="0" cellspacing="0" cellpadding="4">
			<tr>
				<td align="center" height="200" valign="top">
					<label id="newslist"></label>
				</td>
			</tr>
		</table>
		<table width="500" border="0" cellspacing="0" cellpadding="4">
			<tr>
				<td align="center">
					<label id="prePage">
						上一页
					</label>
					<label id="nextPage">
						下一页
					</label>
				</td>
			</tr>
		</table>
    </body>
</html>
 

 注意代码中的注释。

分享到:
评论

相关推荐

    操作系统综合实践三种存储管理的地址换算过程C++实现带论文

    由于连续分配方式会形成许多“碎片”,虽然可通过“紧凑”的方法...根据离散的单位不同产生了分页和分段式存储管理,又由他们的结合产生了段页式存储管理,本论文研究的是用C++语言描述这三种存储管理的地址换算过程。

    Php 分页类 方便

    这里把所有参数都写完的一种方式,其实可以根据不同的需求而省略一些参数的, 这个在后面有介绍,现在把里面的所有参数都做个说明 $_GET["page"]: 这个是接收page参数的值,也就是当前页码,而这个page参数是在 第...

    根据模板,freemarker、xDoc、POI三种方式生成Word文档(含jar包)

    通过三种不同的方式(freemarker+jfreechart、xDoc、POI),根据模板创建Word文件。可以动态修改Word中表格(table)、图表(chart)等数据。导入工程后,可直接运行xxxDemo文件,查看文档生成效果。详见压缩包中的...

    ASP.NET程序中常用的三十三种代码

    当文件在不同目录下,需要获取数据库连接字符串(如果连接字符串放在Web.config,然后在Global.asax中初始化) 31. 变量.ToString() 32、变量.Substring(参数1,参数2); 33.在自己的网站上登陆其他网站:(如果你...

    艺帆精美三防手机网站模板三防手机官方网站源码

    与传统中通过表格(table)布局定位的方式不同,它可以实现网页页面内容与表现相分离。 提及DIV+CSS组合,还要从XHTML说起。XHTML是一种在HTML基础上优化和改进的新语言,目的是基于XML应用与强大的数据转换能力,...

    W78CMSasp企业网站管理系统(中英繁三语版)v140424

    本系统为中英文双语,繁体为js切换!... 显示设置:后台可设置各栏目显示条数、分页记录数等。 自定义导航:新增修改导航菜单、菜单排序等。 SQL注入:后台可设置SQL防注入参数等,SQL注入记录,可

    虚拟存储器(OPT,FIFO,LRU),带三份报告,课程设计

    它是采用一定的方法将一定的外存容量模拟成内存,同时对程序进出内存的方式进行管理,从而得到一个比实际内存容量大得多的内存空间,使得程序的运行不受内存大小的限制。虚拟存储区的容量与物理主存大小无关,而受限...

    毕业设计:ASP教师信息管理系统设计(源代码)

    1、用户登陆注册,可以实现单点登陆到三个不同的后台 2、首页面要有一个查询,这个查询要求通过编号来对教师信息来进行查询。 3、普通用户后台,可以实现对个人资料进行修改,可以对超级管理员进行留言。 4、普通...

    ASP教师信息管理系统设计(源代码+毕设文档).zip

    1、用户登陆注册,可以实现单点登陆到三个不同的后台 2、首页面要有一个查询,这个查询要求通过编号来对教师信息来进行查询。 3、普通用户后台,可以实现对个人资料进行修改,可以对超级管理员进行留言。 4、普通...

    70款经典Dreamweaver插件

    print 支持三种打印页面连接,文字连接、图片连接 preloaddisplay 预先加载页面,如果你的网站下载的速度比较慢,用这个比较好。 swftext 将Drm和Flash结合起来了,选择文本,执行该Command,swf动画就轻易的生成了 ...

    基于Vue+SpringCloud博客的设计与实现 有论文

    用户会员中心:SVIP与VIP,定时任务/RabbitMQ延迟队列/登录验证三种判定会员截止时间到期用邮箱去提醒 用户支付中心:我的钱包和支付宝支付以及打印我的账单,内网穿透获得异步通知作为结果判定标志,原始支付的普通...

    QT编写的可换肤的中文双拼输入法可执行文件

    12:界面布局、字库算法、界面切换100%首创处理,与任何网上的Qt输入法处理方式和布局截然不同。、 13:用法简单极致,只需要在项目中添加输入法界面类(共三个文件frminput.h/frminput.cpp/frminput.ui),然后在...

    《计算机应用基础》第四章课后答案.doc.doc

    题目10 为满足不同用户对外设的应用需求,设备管理的排队策略至少满足() 设备独立于CPU 优先级高优先 三者的结合正确 先到先服务 正确答案是:三者的结合 题目11 用户接口叙述正确的是() 程序调用方式最好,可以...

    网站内容管理系统免费版本

    10) 多样化的文章输入方式 文章输入支持HTML编辑、ubb代码、普通输入三种方式。 11) 文章标题颜色变换,采用ubb嵌入式,这个功能相信对大家来说非常实用 12) 自定义全能JS 可以实现图片文章个性化...

    Java课程设计-基于JavaWeb和Mysql实现的宿舍管理系统源码带数据库+详细说明文档.zip

    1. 用户登录模块 :超级管理员、宿舍管理员、学生三种不同角色的用户登录系统,呈现不同的界面,添加过滤器,没登陆的则不能访问其它界面 2. 超级管理员模块 :超级管理员具有宿舍管理员管理、学生管理、宿舍楼管理...

    ASP.NET程序中常用的三十三种代码.txt

    ASP.NET程序中常用的三十三种代码 1. 打开新的窗口并传送参数:  传送参数: response.write("&lt;script&gt;window.open(’*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"’)&lt;/script&gt;")  接收参数: ...

    ESPCMS易思企业网站管理系统

    三、订单模块:支持订单组合、产品选择、订单在线支付(在线支持方式包括:支付宝、财付通、Moneybookers、PayPal)、订单单据打印、支持条码管理、发货方式自定义、财务单据管理、打折等常见订单功能; 四、营销...

    中关村报价系统源码

    # 新增栏目、品牌、价格,可以继续设置三者之间的关联性,并自动生成节点。 # 在原有的资讯频道(手机、数码相机、摄像机、MP3/MP4、GPS、笔记本、DIY硬件、台式机)的基础上。新增新闻、导购、评测、行情等资讯类前台...

Global site tag (gtag.js) - Google Analytics