公司之前的项目是利用杨涛封装的分页,总的来说还是挺强大的,但是缺点是,每次刷新数据,都需要页面进行刷新。所以,我们就利用js封装了一个利用ajax局部刷新页面的方法。
话不多说,上代码
/*
* AJAX Pager
* 2017.07.19 Version 1.0
*/
(function (window, $) {
var ajaxPager = window.ajaxPager = {
opts: {
pageSize: 12,
preText: "<<", //pre
nextText: ">>", //next
firstText: "首页", //First
lastText: "尾页", //Last
shiftingLeft: 3,
shiftingRight: 3,
pagetotalpage: 0,
preLeast: 2,
nextLeast: 2,
showFirst: true,
showLast: true,
url: "",
type: "POST",
dataType: "JSON",
searchParam: {},
beforeSend: null,
success: null,
complete: null,
bodyDataContainer: "tbodyContainer",
colModel: null,
tablecolspan: 10,
error: function () {
sweetAlert("抱歉,请求出错,请重新请求!");
},
pageIndex: 1,
totalCount: 0,
totalPage: 0,
isSearch:null
},
pagerElement: null,
commonHtmlText: {
spanHtml: "<span class='{0}'>{1}</span>",
pageIndexHtml: "<a href='javascript:void(0)' onclick='ajaxPager.pageClick({0},{1},{2})'>{3}</a>",
rightHtml: "<span class='text'> 共 {0} 条数据, 跳转至第</span> <input type='text' id='txtToPager' value={1} /><span class='text'>页</span> <button id='btnJump' onclick='ajaxPager.jumpToPage();return false;' >跳转</button>",
clearFloatHtml: "<div style='clear:both;'></div>",
stringEmpty: "",
checkboxValue: "<td><input type='checkbox' class='checkboxes' name='ids' value='{0}'/></td>",
buttonvalue: '<a title="{0}" class="btn mini blue thickbox mythickbox" style="" href="{1}"><i class="{2}"></i>{3}</a>',
tdcolvalue: '<td title="{0}">{1}</td>',
isforbiddenvalue: '<td><div style="height: 15px;" class="UesdOrNot" {0}><p type="checkbox" activation="activation" data-used="{1}" name="IsUsed" usedValue="{2}" activateUrl="{3}"></p> </div></td>',
tbemptycontent: "<td>{0}</td>",
tremptycontent: "<tr>{0}</tr>"
},
init: function (obj, op) {
debugger;
var _self = this;
_self.opts = $.extend({}, _self.opts, op);
_self.pagerElement = obj;
if (_self.opts.isSearch)
{
_self.opts.pageIndex = 1;
}
_self.doPage(_self.opts.pageIndex, _self.opts.pageSize, _self.opts.searchParam);
return _self.opts;
},
doPage: function (index, pageSize, searchParam) {
var _self = this;
_self.opts.pageIndex = index;
_self.opts.pageSize = pageSize;
_self.opts.searchParam = searchParam;
$.ajax({
type: _self.opts.type,
data: $.extend(_self.opts.searchParam || {}, {
pageIndex: _self.opts.pageIndex,
pageSize: _self.opts.pageSize || 10
}),
dataType: _self.opts.dataType,
url: _self.opts.url,
beforeSend: function () {
_self.opts.beforeSend();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
indexLoadTipNoVeil(false);
_self.opts.error(XMLHttpRequest, textStatus, errorThrown);
},
success: function (data) {
if (_self.opts.success == null || _self.opts.success.trim() == "") {
_self.drawDataTable(data);
} else {
_self.opts.success(data);
}
//初始化禁用启用按钮
///启用未启用操作
$("[activation='activation']").each(function () {
//设置向左浮动
if ($(this).parent().attr("iMarginLeft") != "" && $(this).parent().attr("iMarginLeft") != undefined) {
$(this).css("margin-left", $(this).parent().attr("iMarginLeft") + "px");
}
if ($(this).attr("usedValue") == 1) {
$(this).append(isusedHtml);
}
else {
$(this).append(isusedFalseHtml);
}
});
$("[activation='activation']")
.click(function () {
isUsedClick($(this));
});
//初始化按钮
tb_init('.mythickbox');
//后台返回数据格式:{"total":0,"items":[],"pagetotalpage": 总页数}
_self.opts.totalCount = data.pagetotalcount;
_self.opts.pagetotalpage = data.pagetotalpage;
_self.getTotalPage();
if (_self.opts.totalCount > 0 && _self.opts.pageIndex > 0) {
var pageTextArr = new Array;
_self.createPreAndFirstBtn(pageTextArr);
_self.createIndexBtn(pageTextArr);
_self.createNextAndLastBtn(pageTextArr);
_self.renderHtml(pageTextArr);
}
indexLoadTipNoVeil(false);
},
complete: function () {
_self.opts.complete();
}
});
},
getTotalPage: function () {
var _self = this;
_self.opts.totalPage = _self.opts.pagetotalpage;
},
createPreAndFirstBtn: function (pageTextArr) {
var _self = this;
if (_self.opts.pageIndex == 1) {
if (_self.opts.showFirst)
pageTextArr.push(_self.createSpan(_self.opts.firstText, 'disenable'));
pageTextArr.push(_self.createSpan(_self.opts.preText, 'disenable'));
} else {
if (_self.opts.showFirst) {
pageTextArr.push(_self.createIndexText(1, _self.opts.firstText));
}
pageTextArr.push(_self.createIndexText(_self.opts.pageIndex - 1, _self.opts.preText));
}
},
createNextAndLastBtn: function (pageTextArr) {
var _self = this;
if (_self.opts.pageIndex == _self.opts.totalPage) {
pageTextArr.push(_self.createSpan(_self.opts.nextText, 'disenable'));
if (_self.opts.showLast)
pageTextArr.push(_self.createSpan(_self.opts.lastText, 'disenable'));
} else {
pageTextArr.push(_self.createIndexText(_self.opts.pageIndex + 1, _self.opts.nextText));
if (_self.opts.showLast)
pageTextArr.push(_self.createIndexText(_self.opts.totalPage, _self.opts.lastText));
}
},
createIndexBtn: function (pageTextArr) {
/*
前:当前页 > 偏移量 + 至少保留 + 1
后:当前页 < 总页码 - 偏移量 - 至少保留
*/
var _self = this;
var shiftingLeftStart = _self.opts.shiftingLeft + _self.opts.preLeast + 1;
var shiftingRightStart = _self.opts.totalPage - _self.opts.shiftingRight - _self.opts.nextLeast - 1;
/*页码*/
if (_self.opts.pageIndex > shiftingLeftStart) {
for (i = 1; i <= _self.opts.preLeast; i++) {
pageTextArr.push(_self.createIndexText(i, i));
}
pageTextArr.push(_self.createSpan('...'));
for (i = _self.opts.pageIndex - _self.opts.shiftingLeft; i < _self.opts.pageIndex; i++) {
pageTextArr.push(_self.createIndexText(i, i));
}
} else {
for (i = 1; i < _self.opts.pageIndex; i++) {
pageTextArr.push(_self.createIndexText(i, i));
}
}
pageTextArr.push(_self.createSpan(_self.opts.pageIndex, 'current'));
if (_self.opts.pageIndex <= shiftingRightStart) {
for (i = _self.opts.pageIndex + 1; i < _self.opts.pageIndex + 1 + _self.opts.shiftingRight; i++) {
pageTextArr.push(_self.createIndexText(i, i));
}
pageTextArr.push(_self.createSpan('...'));
for (i = _self.opts.totalPage - 1; i <= _self.opts.totalPage; i++) {
pageTextArr.push(_self.createIndexText(i, i));
}
} else {
for (i = _self.opts.pageIndex + 1; i <= _self.opts.totalPage; i++) {
pageTextArr.push(_self.createIndexText(i, i));
}
}
},
renderHtml: function (pageTextArr) {
var _self = this;
var pageText = _self.commonHtmlText.stringEmpty;
for (var i = 0; i < pageTextArr.length; i++) {
pageText += pageTextArr[i];
}
_self.pagerElement.html(pageText).append(stringFormat(_self.commonHtmlText.rightHtml, _self.opts.totalCount, _self.opts.pageIndex)).append(_self.commonHtmlText.clearFloatHtml);
},
createSpan: function (text, className) {
var _self = this;
var classnameValue = className ? className : _self.commonHtmlText.stringEmpty;
return stringFormat(_self.commonHtmlText.spanHtml, classnameValue, text);
},
createIndexText: function (index, text) {
var _self = this;
return stringFormat(_self.commonHtmlText.pageIndexHtml, index, _self.opts.pageSize, JSON.stringify(_self.opts.searchParam), text);
},
jumpToPage: function () {
var _self = this;
indexLoadTipNoVeil(true);
var $txtToPager = $("#txtToPager", _self.pagerElement);
var index = parseInt($txtToPager.val());
if (!isNaN(index) && index > 0 && index <= _self.opts.totalPage) {
_self.doPage(index, _self.opts.pageSize, _self.opts.searchParam);
} else {
$txtToPager.focus();
}
},
pageClick: function (index, pageSize, searchParam) {
var _self = this;
indexLoadTipNoVeil(true);
_self.doPage(index, pageSize, searchParam);
},
drawDataTable: function (dataResult) {
var _self = this;
var data = dataResult.items;
var tbodycontainer = $("#" + _self.opts.bodyDataContainer);
tbodycontainer.empty();
if (data != null && data.length > 0) { //绘制数据
for (var i = 0; i < data.length; i++) {
var m = data[i];
//利用参数绘制table中的内容
var tabletdValue = "";
if (_self.opts.colModel == null) {
} else {
$(_self.opts.colModel)
.each(function (colindex) {
var col = _self.opts.colModel[colindex];
//需要隐藏的数据
if (col.hidden != undefined && col.hidden == true) {
tabletdValue = tabletdValue + "<td class='hide' name=" + col.Name + ">" + m[col.Name] + "</td>";
}
//是复选框
else if (col.ischeckbox != undefined && col.ischeckbox == true) {
var tdCheckValue = stringFormat(_self.commonHtmlText.checkboxValue, m.ID);
tabletdValue = tabletdValue + tdCheckValue;
}
//是否是按钮 数组
else if (Object!=null&&Object.prototype!=null&&Object.prototype.toString.call(col) === '[object Array]') {
var buttoncontent = "";
$(col)
.each(function (buttonindex) {
var buttoncol = col[buttonindex];
if (buttoncol.isbutton != undefined && buttoncol.isbutton == true) {
//按钮title与展示的文字
var titlecontent = "titleValue";
//按钮展示的图标
var buttonicon = "icon-edit";
var url = "";
//弹框参数
var thickboxparamValue = "";
//titlevalue需要展示实体中的内容
if (buttoncol.titleName != undefined) {
titlecontent = m[buttoncol.titleName];
}
if (buttoncol.titleValue != undefined) {
titlecontent = buttoncol.titleValue;
}
if (buttoncol.iconclass != undefined) {
buttonicon = buttoncol.iconclass;
}
if (buttoncol.thickboxparam != undefined) {
thickboxparamValue = buttoncol.thickboxparam;
}
if (buttoncol.buttonhref != undefined) {
var buttonurlArray = {}; //{ "id": m.ID };
if (buttoncol.buttonparam != undefined) {
var butonparamvalue = buttoncol.buttonparam;
for (var bparam in butonparamvalue) {
buttonurlArray[bparam] = m[butonparamvalue[bparam]];
}
}
url =
joinUrl(buttoncol.buttonhref,
buttonurlArray,
thickboxparamValue);
}
var buttonColValue =
stringFormat(_self.commonHtmlText.buttonvalue,
titlecontent,
url,
buttonicon,
titlecontent);
buttoncontent = buttoncontent + buttonColValue;
}
});
tabletdValue = tabletdValue + stringFormat(_self.commonHtmlText.tbemptycontent, buttoncontent);
}
//启用禁用
else if (col.isforbidden != undefined && col.isforbidden == true) {
// stringFormat(isforbiddenvalue)
//偏移量
var iMarginLeft = "";
var usedvalue = 0;
var url = "";
if (col.iMarginLeft != undefined) {
iMarginLeft = "iMarginLeft='" + col.iMarginLeft + "'";
}
if (col.usedname != undefined) {
if (m[col.usedname] == true) {
usedvalue = 1;
}
}
if (col.usedhref != undefined) {
var usedparamArray = {}; //{ "id": m.ID };
if (col.usedparam != undefined) {
var usedparam = col.usedparam;
for (var bparam in usedparam) {
usedparamArray[bparam] = m[usedparam[bparam]];
}
}
url = joinUrl(col.usedhref, usedparamArray);
}
tabletdValue = tabletdValue + stringFormat(_self.commonHtmlText.isforbiddenvalue,
iMarginLeft,
usedvalue,
usedvalue,
url);
//tbodycontainer
// .append(stringFormat(_self.commonHtmlText.isforbiddenvalue,
// iMarginLeft,
// usedvalue,
// usedvalue,
// url));
}
//正常数据绘制
else {
var content = m[col.name];
if (col.contentfunction != undefined) {
//自定义函数所需要的参数
if (col.functionparam != undefined && col.functionparam.length > 0) {
var param=new Array(col.functionparam.length);
for (var p = 0; p < col.functionparam.length; p++) {
param[p] = m[col.functionparam[p]];
}
content = col.contentfunction(param);
} else {
content = col.contentfunction(content);
}
}
var subContent = "";
if (content != null) {
subContent = content.toString();
}
if (col.titleName != undefined && col.titleName !== col.name) {
subContent = m[col.titleName];
}
if (col.valueLength != undefined &&
subContent != null &&
subContent.trim() != "" &&
subContent.length > col.valueLength) {
subContent = content.substring(0, col.valueLength);
}
//当展示内容与title不一致
if (col.contentIsHtml && col.titleName != undefined) {
content = m[col.titleName];
}
var tdValue = stringFormat(_self.commonHtmlText.tdcolvalue, content, subContent);
//tbodycontainer.append(tdValue);
tabletdValue = tabletdValue + tdValue;
}
});
}
tbodycontainer.append(stringFormat(_self.commonHtmlText.tremptycontent, tabletdValue));
};
} else {
//没有数据,清空页码数据,添加没有数据提示
_self.pagerElement.html("");
var noDatavalue = '<tr><td colspan="' + _self.opts.tablecolspan + '"><p class="nodata-index">没有找到您要的相关数据!</p></td></tr>';
tbodycontainer.html(noDatavalue);
}
}
}
$.fn.llAjaxPager = function (option) {
return ajaxPager.init($(this), option);
};
})(window, jQuery);
另外还有一个辅助方法和页面样式
页面样式
/**pager**/
#pager {
padding: 0px 10px;
float: right;
}
#pager span {
display: block;
float: left;
padding: 0.3em 0.8em;
margin-right: 5px;
margin-bottom: 5px;
}
#pager span.current {
background: #26B;
color: #fff;
border: solid 1px #AAE;
}
#pager span.disenable {
color: #999;
border-color: #999;
background: #fff;
border: solid 1px #AAE;
}
#pager span.text {
padding: 0.3em 0;
color: #999999;
}
#pager a {
display: block;
float: left;
padding: 0.3em 0.8em;
margin-right: 5px;
margin-bottom: 5px;
text-decoration: none;
border: solid 1px #AAE;
color: #15B;
}
#pager a:hover {
border: solid 1px #26B;
color: #26B;
}
#pager input[type=text] {
padding: 0px 2px;
border: solid 1px #AAE;
22px;
height: 28px;
line-height: 28px;
margin-bottom: 5px;
margin-right: 5px;
padding: 0 3px;
float: left;
text-align: center;
}
#pager button {
cursor: pointer;
border: solid 1px #AAE;
height: 30px;
line-height: 30px;
float: left;
margin-right: 5px;
margin-bottom: 5px;
padding: 0px 3px;
color: #404040;
background: white;
}
#pager button:hover {
border: solid 1px #26B;
color: #26B;
}
辅助方法
/// <summary>辅助方法:格式化字符串</summary>
window.stringFormat = function () {
if (arguments.length == 0)
return null;
var str = arguments[0];
for (var i = 1; i < arguments.length; i++) {
var reg = new RegExp('\{' + (i - 1) + '\}', 'gm');
str = str.replace(reg, arguments[i]);
}
return str;
}
/// <summary>parseURL</summary>
window.parseURL = function (url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':', ''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function () {
var ret = {},
seg = a.search.replace(/^?/, '').split('&'),
len = seg.length, i = 0, s;
for (; i < len; i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(//([^/?#]+)$/i) || [, ''])[1],
hash: a.hash.replace('#', ''),
path: a.pathname.replace(/^([^/])/, '/$1'),
relative: (a.href.match(/tps?://[^/]+(.+)/) || [, ''])[1],
segments: a.pathname.replace(/^//, '').split('/')
};
}
//拼接url
//urlparam url的参数 格式example:var urlparam=new{"a":"b","c":"d"}
//thickboxparam 弹框参数 example:TB_iframe=true&height=300&width=400
window.joinUrl = function (url, urlparam, thickboxparam) {
var joinUrl = url;
//拼接地址参数
if (urlparam != null) {
if (url.indexOf('?') <= 0) {
joinUrl = joinUrl + "?";
}
var j = 0;
for (var i in urlparam) {
if (j === 0) {
joinUrl = joinUrl + i + "=" + urlparam[i];
} else {
joinUrl = joinUrl + "&" + i + "=" + urlparam[i];
}
j++;
}
}
//拼接弹框参数
if (thickboxparam != null && thickboxparam.trim() != "") {
if (joinUrl.indexOf('?') <= 0) {
joinUrl = joinUrl + "?" + thickboxparam;
} else {
joinUrl = joinUrl + "&" + thickboxparam;
}
}
return joinUrl;
}
现在,详细描述一下流程:
首先,在使用的时候,需要先初始化一下:
$('#pager').llAjaxPager({
url: ajaxUrl,
type: "post",
bodyDataContainer: "tbodyContainer",
tablecolspan: 10,
isSearch: isSearch,
colModel:
[
{ name: 'TrainingInstitutionId', hidden: true, ischeckbox: true },
{ name: 'TrainingInstitutionName', hidden: false, valueLength: 5 },
{ name: 'SumStudentCount', functionparam: ["SumStudentCount", "TrainingInstitutionId"], contentfunction: showSumStudentCountUrl, hidden: false },
[{ isbutton: true, titleValue: '全部数据', iconclass: "icon-edit", thickboxparam: "TB_iframe=true&height=500&width=580", buttonhref: editUrl, buttonparam: buttonparam }],
],
beforeSend: function () {
},
complete: function () {
}
});
传递的元素,是存储分页的地方。其中bodyDataContainer 是最终存储数据的地方,所以,在这个demo中,表头是需要自己绘制。在这里需要说明一下:封装的这个分页插件,参数的传递在使用的时候,我是利用from表单来获取和传递的,所以,暂且不知道,直接传递的效果(ps:利用表单获取,在之前的项目中,方法已经完全实现,所以,没有再去修改),获取参数的例子如下:
var data = $("#searchData").serialize();
这样利用最原始的url与之拼装使用即可。
说一下参数的用途吧:首先,在这个分页中,支持按钮(包括thickbox的弹窗按钮),列自定义function的传递,和复选框的初始化,及其参数的隐藏和title的展示等。
基础字段有 name:是指实体的字段名称。 valuelength :是指是否需要截取字符串。
{ name: 'SumStudentCount', functionparam: ["SumStudentCount", "TrainingInstitutionId"], contentfunction: showSumStudentCountUrl, hidden: false },
这句代码是传递的自定义参数,处理数据的,首先 functionparam 是指function需要的参数集合 contentfunction 是指自定义的函数 。