首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

三种不同的分页形式

2012-08-31 
三种不同的分页方式习惯了ext的Ext.grid.GridPanel与Ext.data.Store封装好了的分页方式以及ajax处理方式Ex

三种不同的分页方式

习惯了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 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" />        <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" value="10" name="num_display_entries" id="num_display_entries" value="2" name="num_edge_entries" id="num_edge_entries" 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 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>
?

?注意代码中的注释。

热点排行