項目用到ajax技術的查詢,查詢結果很多時候要分頁展示。這兩天摸索了一下,在這里做一總結,方便自己隨時查看,
也方便后人參考。
這里的順序遵從從前台頁面到后台控制器,業務層,Dao層,Mapper
下面先講頁面,頁面js代碼如下:
- <span style="font-size:14px;">/* 全局變量 */
- var userCount;//符合查找條件的用戶總頁數,分頁參考
- var pageIndex = 0;//當前頁,默認為0
- var pageSize = 8;//每頁顯示個數為8
- //按條件查找用戶
- function searchUser(index,size) {
- var findTerm = $("#serchTerm").val();
- var provinceId = $('#province').val();
- var cityId = $('#city').val();
- $.ajax({
- type : "POST",
- url : "user/findContactsAjax",
- cache : false,
- data : {
- provinceId : provinceId,
- cityId : cityId,
- pageIndex:index,
- pageSize:size
- },
- async : true,
- error : function() {
- alert("網絡異常!");
- },
- success : function(data) {
- <span style="white-space:pre"> </span>userCount=Math.ceil(data[0].userCount/8);<span style="white-space:pre"> </span>var page='<div id="userPage" align="center" ><font size="2">共'
- +userCount+'頁</font> <font size="2">第'
- +(pageIndex+1)+'頁</font> <a href="javascript:void" onclick="GoToFirstPage()" id="aFirstPage" >首頁</a> '
- +'<a href="javascript:void" onclick="GoToPrePage()" id="aPrePage" >上一頁</a> '
- +'<a href="javascript:void" onclick="GoToNextPage()" id="aNextPage" >下一頁</a> '
- +'<a href="javascript:void" onclick="GoToEndPage()" id="aEndPage" >尾頁</a> ';
- page+='</div>';
- $("#serchResult").append(page);
- document.getElementById("dltitle").innerHTML = "查找結果如下";
- }
- }
- });
- }
- //首頁
- function GoToFirstPage() {
- pageIndex = 0;
- searchUser( pageIndex, pageSize);
- }
- //前一頁
- function GoToPrePage() {
- pageIndex -= 1;
- pageIndex = pageIndex >= 0 ? pageIndex : 0;
- searchUser( pageIndex, pageSize);
- }
- //后一頁
- function GoToNextPage() {
- if (pageIndex + 1 < userCount) {
- pageIndex += 1;
- }
- searchUser( pageIndex, pageSize);
- }
- //尾頁
- function GoToEndPage() {
- pageIndex = userCount - 1;
- searchUser( pageIndex, pageSize);
- }</span>
控制層代碼如下:
- @RequestMapping("findContactsAjax")
- public @ResponseBody
- Map<String, Object> findContactAjax(String provinceId,String cityId,String pageIndex,String pageSize) {
- List<User> listUsers = userDao.selectUserByProvinceAndCity(provinceId, cityId,pageIndex,pageSize)
- }
- map.put("user", listUsers);
- return map;
- }
Dao層:
- List<User> selectUserByProvinceAndCity(@Param("provinceId") Integer provinceId, @Param("cityId") Integer cityId,
- @Param("pageIndex") Integer pageIndex,@Param("pageSize") Integer pageSize);
mapper文件:
- <select id="selectUserByProvinceAndCity" resultMap="BaseResultMap">
- SELECT *,
- (SELECT COUNT(*) FROM user_user_t
- province_id=#{provinceId}
- AND
- city_id=#{cityId}) AS userCount
- FROM user_user_t
- province_id=#{provinceId}
- AND
- city_id=#{cityId}
- LIMIT #{pageIndex},#{pageSize}
- </select>
User實體
- public class User {
- private Integer userId;
- private String userName;
- private Integer provinceId;
- private Integer cityId;
- private Integer userCount;//滿足查詢條件的用戶數目,作為分頁的依據
- }
- 《轉:http://blog.csdn.net/gisredevelopment/article/details/39084945》