使用ajax实现分页技术

2019-09-14 06:51:58王冬梅

ajax分页效果图如下:

首先,先看 HTML 代码和 CSS 代码,我们需要一个 table 和一个 footer:

<div id="global">
<div id="table">
 <table>
 <col width="19%">
 <col width="19%">
 <col width="19%">
 <col width="19%">
 <col width="24%">
 <tr>
 <th>日期</th>
 <th>时间</th>
 <th>事件</th>
 <th>报警画面</th>
 <th>事件备注</th>
 </tr>
 </table>
 </div>
 <div id="footer">
 <span id="summary"></span>
 <ul id="pagination">
 <li id="01">首页</li>
 <li id="02">上一页</li>
 <li id="03">下一页</li>
 <li id="04">最后一页</li>
 </ul>
 <div id="select">
 <span>跳转到 </span>
 <input type="text" name="page_num">
 <span> 页 </span>
 <input type="button" name="go_btn" value="跳转">
 </div>
 </div>
</div>

下面是 css 代码:

#global{
 position: relative;
}
#table{
 position: absolute;
 top:19%;
 left:1.6%;
 width: 55%;
}
#table textarea{
 width: 10vw;
 height: 10vh;
 background-color: transparent;
 color: #fff;
 border-width: 0;
 text-align: center;
}
table, th, td {
 border: 0.2px solid rgba(60,166,206,0.2);
 border-collapse: collapse;
 color:rgba(60,166,206,1); 
}
th, td {
 padding: 3px;
 text-align: center;
 font-size: 1.6vmin;
}
td{
 background: rgba(2,29,54,1);
}
th{
 background: rgba(20,29,54,1);
 padding: 1.8% 0;
 color: rgba(255,255,255,0.8);
}
#footer{
 position: absolute;
 bottom:5vh;
 left:7vw;
 text-align: center;
 color: rgba(60,166,206,1);
}
#pagination{
 display: inline-block;
}
#pagination li{
 display: inline;
}
#select{
 display: inline-block;
 margin-left: 40px;
}
#select input[type="text"]{
 width: 30px;
 height: 20px;
 background-color: #000;
 border-width: 1px;
}
#select input[type="button"]{
 width: 40px;
 height: 23px;
 background: #000;
 border:none;
}
ul li{
 cursor: pointer;
}

初始化开始日期,结束日期,请求的页数,请求的每页数量,总共有多少页数据,并通过 ajax 将这些数据传给后台提供的 API 数据接口,进而从数据库中获取到数据,然后可以在前端展示:

var start_date = "2017-01-01", end_date = "2017-01-08";
var pageNo = 1;
var pageSize = 4;
var pages = 0;

如何获取表格的数据并将其 append 到前端?如何获取分页的数据并将其 append 到前端?使用下面我们定义的函数:

loadData(pageNo, pageSize);

接下来看这个函数如何跟 API 数据接口沟通:

function loadData(pageNo, pageSize){
 $(".detail").remove(); //每次重新从 API 数据接口获取数据都要先清除原先表格 `<tr>` 的内容
 $.ajax({
 url: "/history_alarm",
 type: "POST",
 data: JSON.stringify({date:date, page_num:pageNo, page_size:pageSize}),
 success:function(result){
 var results = JSON.parse(result);
 var list = results.alarm;
 var totalCount = results.alarm_count;
 pages = results.page_count;
 if(list.length != 0){
  for(var i=0; i<list.length; i++){
  var alarm_id = list[i].alarm_id;
  var alarm_pic = list[i].alarm_pic;
  var date = list[i].date;
  var event = list[i].event;
  var time = list[i].time;
  var remark = list[i].remark;
  appendData(alarm_id, alarm_pic, date, event, time, remark);
  addEvent(alarm_id);
  }
  $("#table").show();
  $("#footer").show();
  displayFooter(totalCount, pages, pageNo);
 } else{
  $("#table").hide();
  $("#footer").hide();
 }
 },
 error:function(){
 //error handle function
 }
 });
 }