记载无刷新分页的实现-以备查看
鉴于网上大多数不完整,所以搜刮各类资源自行整合之,以期之昂也!
主要有三个步骤:
1。在action中将需要的json数据输出。
2。利用写好的页数插件,并修改传递页数。
3。利用ajax 实现数据的获取以及页数的传递。
其action为:
public class Testaction2 extends ActionSupport{
/**
*
*/
public BGlyRoleServiceImpl bGlyRoleServiceImpl;
public void setBGlyRoleServiceImpl(BGlyRoleServiceImpl bGlyRoleServiceImpl) {
this.bGlyRoleServiceImpl = bGlyRoleServiceImpl;
}
private int linshipage;
private static final long serialVersionUID = 1L;
@SuppressWarnings("unchecked")
public String list() {
HttpServletRequest request = ServletActionContext.getRequest();
int pageSize = 5;//偏移量,每次要查询出的pageSize条记录
int pageNow = Integer.valueOf(request.getParameter("page"));
//当前页码
int pageCount = 0;//总页数
List<BRole> list = new ArrayList<BRole>();
try {
int count = (int) bGlyRoleServiceImpl.Count("select count(*) from BRole");//总记录数
pageCount = (count + pageSize - 1) / pageSize;//计算出总页数
if (pageNow < 1) {
pageNow = 1;
}
if (pageNow > pageCount) {
pageNow = pageCount;
}
System.out.println("pageNow"+pageNow);
linshipage=pageNow;
//hql的分页查询
list=bGlyRoleServiceImpl.findAllListBypage("from BRole", linshipage, pageSize);
for (Iterator<BRole> iterator = list.iterator(); iterator.hasNext();) {
BRole bRole = (BRole) iterator.next();
System.out.println(bRole.toString());
}
StringBuffer dataSource = new StringBuffer();
dataSource.append("{\"dataSource\":");
dataSource.append(JsonUtils.listToJson(list));//把list转换为json
System.out.println("-------"+dataSource);
@SuppressWarnings("rawtypes")
Map map = new HashMap();
map.put("pageCount", pageCount);
map.put("pageNow", pageNow);
map.put("count",count);
map.put("pageSize",pageSize );
String s= JsonUtils.mapToJson(map);//把map转换为json
System.out.println("s--map"+s);
dataSource.append(",\"pageSource\":");
dataSource.append(s);// 总页数、当前页码 添加到json
dataSource.append("}");
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/javascript");//数据按照js格式送回去
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.write(dataSource.toString());
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Struts.xml 不需要返回值
<action name="test2-*" class="testAction2" method="{1}">
</action>
jsp为
<table id="sample-table-2" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th class="hidden-480">角色id</th>
<th class="hidden-480">角色</th>
<th>角色所拥有权限</th>
<th>操作</th>
</tr>
</thead>
<tbody id = "datasource">
<tr id ="source">
<td><div id="roleId"></div></td>
<td><div id="roleName"></div></td>
<td><div id="rolePer"></div></td>
<td><div id="bz"></div></td>
<td>
<div class="visible-md visible-lg hidden-sm hidden-xs action-buttons">
<a class="green" href="#" title="修改">
<i class="icon-pencil bigger-130"></i>
</a>
<a class="red" href="#" title="删除">
<i class="icon-trash bigger-130"></i>
</a>
</div>
<div class="visible-xs visible-sm hidden-md hidden-lg">
<div class="inline position-relative">
<button class="btn btn-minier btn-yellow dropdown-toggle" data-toggle="dropdown">
<i class="icon-caret-down icon-only bigger-120"></i>
</button>
<ul class="dropdown-menu dropdown-only-icon dropdown-yellow pull-right dropdown-caret dropdown-close">
<li>
<a href="#" class="tooltip-info" data-rel="tooltip" title="View">
<span class="blue">
<i class="icon-zoom-in bigger-120"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-success" data-rel="tooltip" title="Edit">
<span class="green">
<i class="icon-edit bigger-120"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-error" data-rel="tooltip" title="Delete">
<span class="red">
<i class="icon-trash bigger-120"></i>
</span>
</a>
</li>
</ul>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<form action="test2-list" name="listpage">
<div class="modal-footer no-margin-top">
<div class="text-center">
<ul id="pagination-demo" class="pagination-sm"></ul>
</div>
</div>
</form>
</body>
<script type="text/javascript">
</script>
<script type="text/javascript">
//进入页面时查询的数据
$(document).ready(function(){
var page=1;
jqeryajax(page);
});
// 查询数据的分页跳转
function jqeryajax(page){
$.ajax({
url:'test2-list?page='+page,
type:"POST",
dataType:'json',
success:function(data){
$(data).each(function() {
insertTr(data);
});
}
});
}
function insertTr(data) {
//读取tr里数量
var r = $("#datasource tr").size();
// alert("r"+r);
var num = 0;
if(r < 1){
num = 1;
}else if(r > 1){
$("#datasource").find("tr:not(:first)").remove();
}
var list = data.dataSource;//查询出的数据
var list1 = data.pageSource;//总页数、当前页码
$.each(list1,function(i, item){
// alert("pageSize"+item.pageSize+"pageNow"+item.pageNow);
$("#myspan").html(item.pageCount);
$("#pagenumber").val(item.pageNow);
*//此是调用页数插件的关键并传递页数*
$('#pagination-demo').twbsPagination({
totalPages: item.pageCount,
visiblePages: 3,
version: '1.1',
onPageClick: function (event, page) {
$('#page-content').text('Page ' + page);
}
});
});
$.each(list, function(i, r) {
//克隆已有的表格样式及属性
var row = $("#source").clone();
//将数值填充至表格中
row.find("#roleId").text(r.roleId)
row.find("#roleName").text(r.roleName);
row.find("#rolePer").text(r.rolePer);
row.find("#bz").text(r.bz);
//将此行添加到表格中
row.appendTo("#datasource");
});
// 移除第一行,因为它只有样式没有数据
$("#datasource").children("tr:first").remove();
}
</script>
</body>
其js为
(function ($, window, document, undefined) {
'use strict';
var old = $.fn.twbsPagination;
// PROTOTYPE AND CONSTRUCTOR
var TwbsPagination = function (element, options) {
this.$element = $(element);
this.options = $.extend({}, $.fn.twbsPagination.defaults, options);
this.init(this.options);
};
TwbsPagination.prototype = {
constructor: TwbsPagination,
init: function (options) {
this.options = $.extend({}, this.options, options);
switch (this.options.version) {
case '1.0':
this.currentPages = this.getPages_v_1_0(this.options.startPage);
break;
case '1.1':
this.currentPages = this.getPages_v_1_1(this.options.startPage);
break;
default:
this.currentPages = this.getPages_v_1_1(this.options.startPage);
break;
}
if (this.options.startPage < 1 || this.options.startPage > this.options.totalPages) {
throw new Error('Start page option is incorrect');
}
if (this.options.totalPages <= 0) {
throw new Error('Total pages option cannot be less 1 (one)!');
}
if (!$.isNumeric(this.options.visiblePages) && !this.options.visiblePages) {
this.options.visiblePages = this.options.totalPages;
}
if (this.options.onPageClick instanceof Function) {
this.$element.bind('page', this.options.onPageClick);
}
var tagName = (typeof this.$element.prop === 'function') ?
this.$element.prop('tagName') : this.$element.attr('tagName');
if (tagName === 'UL') {
this.$listContainer = this.$element;
} else {
this.$listContainer = $('<ul></ul>');
}
this.$listContainer.addClass(this.options.paginationClass);
this.$listContainer.append(this.buildListItems(this.currentPages.numeric));
if (tagName !== 'UL') {
this.$element.append(this.$listContainer);
}
this.show(this.options.startPage);
},
show: function (page) {
if (page < 1 || page > this.options.totalPages) {
throw new Error('Page is incorrect.');
}
switch (this.options.version) {
case '1.0':
this.render(this.getPages_v_1_0(page));
break;
case '1.1':
this.render(this.getPages_v_1_1(page));
break;
default:
this.render(this.getPages_v_1_1(page));
break;
}
this.setupEvents();
this.$element.trigger('page', page);
},
buildListItems: function (pages) {
var $listItems = $();
if (this.options.first) {
$listItems = $listItems.add(this.buildItem('first', 1));
}
if (this.options.prev) {
$listItems = $listItems.add(this.buildItem('prev', 1));
}
for (var i = 0; i < pages.length; i++) {
$listItems = $listItems.add(this.buildItem('page', pages[i]));
}
if (this.options.next) {
$listItems = $listItems.add(this.buildItem('next', 2));
}
if (this.options.last) {
$listItems = $listItems.add(this.buildItem('last', this.options.totalPages));
}
return $listItems;
},
buildItem: function (type, page) {
var itemContainer = $('<li></li>'),
itemContent = $('<a></a>'),
itemText = null;
itemContainer.addClass(type);
itemContainer.attr('data-page', page);
switch (type) {
case 'page':
itemText = page;
break;
case 'first':
itemText = this.options.first;
break;
case 'prev':
itemText = this.options.prev;
break;
case 'next':
itemText = this.options.next;
break;
case 'last':
itemText = this.options.last;
break;
default:
break;
}
itemContainer.append(itemContent.attr('href', this.href(page)).text(itemText));
return itemContainer;
},
getPages_v_1_0: function (currentPage) {
var pages = [];
alert("currentPage"+currentPage);
var startPage;
var section = parseInt(currentPage / this.options.visiblePages, 10);
if (currentPage % this.options.visiblePages === 0) {
startPage = (section - 1) * this.options.visiblePages + 1;
} else {
startPage = section * this.options.visiblePages + 1;
}
var endPage = Math.min(this.options.totalPages, (startPage + this.options.visiblePages) - 1);
for (var i = startPage; i <= endPage; i++) {
pages.push(i);
}
return {"currentPage": currentPage, "numeric": pages};
},
getPages_v_1_1: function (currentPage) {
var pages = [];
jqeryajax(currentPage);
//此为修改的关键,链接页数插件和ajax 的 json 数据查询
var half = Math.floor(this.options.visiblePages / 2);
var start = currentPage - half + 1 - this.options.visiblePages % 2;
var end = currentPage + half;
// handle boundary case
if (start <= 0) {
start = 1;
end = this.options.visiblePages;
}
if (end > this.options.totalPages) {
start = this.options.totalPages - this.options.visiblePages + 1;
end = this.options.totalPages;
}
var itPage = start;
while (itPage <= end) {
pages.push(itPage);
itPage++;
}
return {"currentPage": currentPage, "numeric": pages};
},
render: function (pages) {
if (!this.equals(this.currentPages.numeric, pages.numeric)) {
this.$listContainer.children().remove();
this.$listContainer.append(this.buildListItems(pages.numeric));
this.currentPages = pages;
}
this.$listContainer.find('.page').removeClass('active');
this.$listContainer.find('.page').filter('[data-page="' + pages.currentPage + '"]').addClass('active');
this.$listContainer.find('.first')
.toggleClass('disabled', pages.currentPage === 1);
this.$listContainer.find('.last')
.toggleClass('disabled', pages.currentPage === this.options.totalPages);
var prev = pages.currentPage - 1;
this.$listContainer.find('.prev')
.toggleClass('disabled', pages.currentPage === 1)
.data('page', prev > 1 ? prev : 1);
var next = pages.currentPage + 1;
this.$listContainer.find('.next')
.toggleClass('disabled', pages.currentPage === this.options.totalPages)
.data('page', next < this.options.totalPages ? next : this.options.totalPages);
},
setupEvents: function () {
var base = this;
this.$listContainer.find('li').each(function () {
var $this = $(this);
$this.off();
if ($this.hasClass('disabled') || $this.hasClass('active')) return;
$this.click(function () {
base.show(parseInt($this.data('page'), 10));
});
});
},
equals: function (oldArray, newArray) {
var i = 0;
while ((i < oldArray.length) || (i < newArray.length)) {
if (oldArray[i] !== newArray[i]) {
return false;
}
i++;
}
return true;
},
href: function (c) {
return this.options.href.replace(this.options.hrefVariable, c);
}
};
// PLUGIN DEFINITION
$.fn.twbsPagination = function (option) {
var args = Array.prototype.slice.call(arguments, 1);
var methodReturn;
var $set = this.each(function () {
var $this = $(this);
var data = $this.data('twbs-pagination');
var options = typeof option === 'object' && option;
if (!data) $this.data('twbs-pagination', (data = new TwbsPagination(this, options) ));
if (typeof option === 'string') methodReturn = data[ option ].apply(data, args);
});
return ( methodReturn === undefined ) ? $set : methodReturn;
};
$.fn.twbsPagination.defaults = {
totalPages: 0,
startPage: 1,
visiblePages: 5,
href: 'javascript:void(0);',
hrefVariable: '{{number}}',
first: 'First',
prev: 'Previous',
next: 'Next',
last: 'Last',
paginationClass: 'pagination',
onPageClick: null,
version: '1.0'
};
$.fn.twbsPagination.Constructor = TwbsPagination;
$.fn.twbsPagination.noConflict = function () {
$.fn.twbsPagination = old;
return this;
};
})(jQuery, window, document);