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 } }); }
|
新聞熱點
疑難解答
圖片精選