html创建一个存放内容的容器,以及分页的容器:
<div id="content"></div>
<div id="pager"></div>
js如下:
$.ajax({
url: "url",
//headers: {
//"AccessToken" : "token"
//}, //如果需要
type: "GET/POST",
dataType: "json",
success: function(result){
console.log(result);
//获取后台发送过来的JSON数据
jsonData = getJsonData(result.length,result);
//加载数据
pageTo(13,1); // 定义每页显示多少条数据,以及默认显示当前页数为第几页
},
error: function(data){
console.log("error")
}
});
// 创建一个空的数组 用来存放符合要求的在页面上显示的所有数据
var jsonData = [];
function getJsonData(size,result) {
var datas = [];
for (var idx = 0; idx < size; idx++) {
datas.push({
contents : result[idx].title,
id : result[idx].NewsID //定义想要展示的内容
});
}
return datas;
}
//获取当前页数据
function query(cur, size) {
var begin = (cur - 1) * size;
var end = cur * size;
return jsonData.slice(begin, end);
}
//分页函数开始
function pageTo(pageSize, curPage) {
var dataSize = jsonData.length;
//判断当前页数
if (dataSize == 0) {
content.innerHTML = "<span class='no-content'>没有查询到任何数据!</span>";
return;
}
var totalPage = Math.ceil(dataSize / pageSize);
// html推送内容
var datas = query(curPage, pageSize);
var html = "";
for (var index = 0; index < datas.length; index++) {
var data = datas[index];
html = html + "<li>";
html = html + "<a target='_blank' href='href'>" + (data.contents || '') + "</a>";
html = html + "<span>" + (data.id|| '') + "</span>";
html = html + "</li>";
}
content.innerHTML = html;
//pager
var phtml = "<div class='pager'>";
if (curPage == 1) {
phtml = phtml + "<a href='#' class='button no-page'>上一页</a>";
} else {
phtml = phtml + "<a href='#' class='button' onclick='pageTo("+pageSize+","+(curPage-1)+")'>上一页</a>";
}
phtml = phtml + "<input type='text' disabled value='" + curPage + "' onkeypress='goto(this, " + pageSize+ ");'>";
if (curPage == totalPage) {
phtml = phtml + "<a href='#' class='button no-page'>下一页</a>";
} else {
phtml = phtml + "<a href='#' class='button' onclick='pageTo("+pageSize+","+(curPage+1)+")'>下一页</a>";
// phtml = phtml + "<a href='#' class='button' onclick='test("+pageSize+","+curPage+");'>下一页</a>";
}
phtml = phtml + " 共" + totalPage + "页," + dataSize + "条记录</div>";
pager.innerHTML = phtml;
}
//回车跳转,注意控制输入数字:此处未处理
function goto(obj, pageSize){
if(event.keyCode==13){
pageTo(pageSize, parseInt(obj.value));
}
}