分页技术
是一种将所有数据分段展示给用户的技术.用户每次看到的不是全部数据,而是其中的一部分,如果在其中没有找到自习自己想要的内容,用户可以通过制定页码或是翻页的方式转换可见内容,直到找到自己想要的内容为止。
前10条记录:
select * from table limit 0,10
第11至20条记录:
select * from table limit 10,10
第21至30条记录:
select * from table limit 20,10
从上面可以看出规律
(当前页数 - 1 )X 每页条数 , 每页条数
Select * from table limit ($Page- 1) * $PageSize, $PageSize
上代码
控制器部分
public function getlists(Request $request) {
// 获取到当前currentpage 和perpage 每页多少条
$currentPage = (int)$request->input('current_page');
$perage = (int)$request->input('perpage');
$limitprame = ($currentPage -1) * $perage;
$info = DB::table('user_info')-> skip($limitprame)->take($perage)-> get();
$data = [
'status'=> 1,
'data' => [
'data' => $info,
'currentPage' => $currentPage
]
];
return $data;
}
前端blade模板
<h1> 分页demo页面</h1>
<table border="1" cellspacing="0" id="tableWarp">
<tr>
<th>user_id</th>
<th>手机号</th>
<th>昵称</th>
<th>邮箱</th>
</tr>
<tbody id="tbody">
</tbody>
</table>
<div>
<span class="preFn">上一页</span>
<span style="margin:0 10px;">
当前页:<span id="currentPageDom"></span>
</span>
<span class="nextFn" style="margin-right:10px;">下一页</span>
<input id="input1" type="text">
<button class="submitBtn">跳转</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function getInfo (currentpage,perpage) {
$.ajax({
type: "GET",
url: "getlists",
data: {
current_page:currentpage,
perpage:perpage
},
dataType: "json",
success: function(data){
if (data.status == 1) {
var str = ''
var currentpage = data.data.currentPage
$.each(data.data.data,function(i,item){
str += ' <tr><td>'+ item.user_id +' </td>\
<td>'+ item.phone +'</td>\
<td>'+ item.nickname +'</td>\
<td>'+ item.email +'</td></tr>'
});
$('#currentPageDom').html(currentpage)
$('#tbody').html(str)
}
}
});
}
$(function(){
getInfo(1,3)
});
$('.preFn').on('click',function() {
//console.log('点击了上一页')
var currentPage = Number($('#currentPageDom').html() )
getInfo(currentPage-1,3)
})
$('.nextFn').on('click',function() {
// console.log('点击了下一页')
var currentPage = Number($('#currentPageDom').html() )
getInfo(currentPage+1,3)
})
$('.submitBtn').on('click',function() {
// 获取input内容
var inputValue = Number($('#input1').val())
getInfo(inputValue,3)
})
</script>
前端传入currentpage当前页以及perpage 每页多少条数据。后端拿到get提交的参数后,进行limit() 处理
这里写的是最最简陋的分页,一些东西还需完善。原谅我的jq代码,主要是想传达php部分怎么写,也原谅我的php代码,因为没写几天。
注:这里使用的是laravel 5.2 新版本的laravel新增了2个替代方法,可以使用 limit 和 offset 方法。

本文介绍了如何在laravel中实现简单的分页功能。通过将数据分段展示,用户可以逐步浏览,控制器部分处理get参数,利用limit()和offset()方法实现分页。虽然示例代码较为基础,但展示了laravel分页的基本思路。
1189

被折叠的 条评论
为什么被折叠?



