分頁進階--ajax+jquery+struts2

  按照上次的分頁邏輯,分頁查詢的業務大概須要幾個「零件」:1.當前頁;2.總頁數;3.跳轉頁。後端須要處理的是:按照傳送過來請求的頁碼返回相應地數據,而且接受初始化參數的請求:總頁碼、第一頁的數據。javascript

  使用ajax請求能夠很輕易地和服務器交互,所須要的數據格式是json。json的好處是能夠把大量的數據格式化成一條字符串,由先後端的程序進行解析並呈現內容。我把查詢到的數據裝入list,並用struts自帶的工具轉換成爲json返回客戶端。html

  前端程序以下:前端

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/pager.js"></script>
</head>
<body>

    <div >
        <table id="content" border="1">

        </table>
    </div>
    <div id="guide">
        <!-- 只輸入數字的輸入框 -->
        <button id="prePage" type="button">上一頁</button> 當前 第 <span id="current"></span> 頁/共 <span id="total"></span> 頁  跳轉到<input id="jumpPage" size="5" type="text" onkeyup='this.value=this.value.replace(/\D/gi,"")'/> <button id="jumpBtn">跳轉到</button>  <button id="nextPage" type="button">下一頁</button>
    </div>
</body>
</html>
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
var totalPage;
var currentPage;
var userlist;
//初始化請求--將當前頁和總頁面初始化 和 list
$(document).ready(function(){
    
    $.get('Init','',function(results){
        $.each(results, function(key, val) {     
             if(key === "current")
                 currentPage = results[key];
             else if(key === "total")
                 totalPage = results[key];
             else if(key == "list"){
                userlist=val;
             }
        });
        currentPage = parseInt(currentPage);
        totalPage = parseInt(totalPage);
        $("#current").text(currentPage);
        $("#total").text(totalPage);
        getUser(userlist);
       
        //console.log(currentPage);
        //console.log(totalPage);
    });
});

//上一頁
$(document).ready(function(){
    $('#prePage').click(function(){
        if(currentPage == 1)
            alert("已至首頁");
        else{
            currentPage = currentPage-1;
            var need=currentPage;
        
            $.get('Pager','need='+need,function(result){
                userlist = result['userList'];
                getUser(userlist);
                $('#current').text(need);
            });
            }
    });
});
//下一頁
$(document).ready(function(){
    $('#nextPage').click(function(){
        if(currentPage == totalPage)
            alert("已至尾頁");
        else{
            currentPage = currentPage+1;
            var need=currentPage;
        
            $.get('Pager','need='+need,function(result){
                userlist = result['userList'];
                getUser(userlist);
                //console.log(need);
                $('#current').text(need);
            });
        }
    });
    
});
//跳轉頁
$(document).ready(function(){
    $('#jumpBtn').click(function(){
        var toPage = $('#jumpPage').val();
        if(toPage != ""){
            toPage = parseInt(toPage);
            if(toPage <= totalPage && toPage >=1)
                $.get('Pager','need='+toPage,function(result){
                    userlist = result['userList'];
                    getUser(userlist);
                    //console.log(need);
                    $('#current').text(toPage);
                });
            else {
                alert("跳轉頁不合法!");
            }
        }
    });
});
//遍歷list並生成table
function getUser(list){
    //先清空再添加
    var table = $('#content');
    table.html("");
    var thead = $("<tr></tr>");
    thead.appendTo(table);
    var tagName = $("<td>id</td>");
    tagName.appendTo(thead);
    tagName = $("<td>name</td>");
    tagName.appendTo(thead);
    tagName = $("<td>sex</td>");
    tagName.appendTo(thead);
    tagName = $("<td>age</td>");
    tagName.appendTo(thead);
    
    for(var k in list){
        var tr=$("<tr></tr>");
        tr.appendTo(table);
        var person = new Object();
        var td;
        
        person.id=userlist[k]['id'];
        person.name=userlist[k]['name'];
        person.sex=userlist[k]['sex'];
        person.age=userlist[k]['age'];
            
        td=$("<td>"+person.id+"</td>");
        td.appendTo(tr);
        td=$("<td>"+person.name+"</td>");
        td.appendTo(tr);
        td=$("<td>"+person.sex+"</td>");
        td.appendTo(tr);
        td=$("<td>"+person.age+"</td>");
        td.appendTo(tr);
        //console.log(person);
    }
}

  後端邏輯爲:java

package ActionPackage;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import model.test_u;
import pagetest.PageService;


public class PageAction extends ActionSupport{
    private HashMap<String,Object> dataMap;
    private List<test_u> userList;
    public List<test_u> getUserList() {
        return userList;
    }
    public void setUserList(List<test_u> userList) {
        this.userList = userList;
    }
    private int size=10;
    public String Pager(){
        HttpServletRequest request = ServletActionContext.getRequest();
        int need = Integer.parseInt(request.getParameter("need"));
        System.out.println("need = "+need);
        PageService ps = new PageService();
        userList = ps.selectLimit((need-1)*size, size);
        return SUCCESS;
    }
    public String Init(){
        System.out.println("訪問了!");
        PageService ps = new PageService();
        int total = ps.getConut()/10;
//        HttpServletResponse response = ServletActionContext.getResponse();
        dataMap = new HashMap<String,Object>();
        dataMap.put("current", 1);
        dataMap.put("total", total);
        List list = ps.selectLimit(1, size);
        dataMap.put("list", list);
//        String jsonString="{\"current\":1,\"totle\":12}"; 
//        try {
//            response.getWriter().print(jsonString);
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        return SUCCESS;
    }
    
    public HashMap<String, Object> getDataMap() {
        return dataMap;
    }
    public void setDataMap(HashMap<String, Object> dataMap) {
        this.dataMap = dataMap;
    }
}

  模型層與DAO層與service層如上篇分頁同樣。jquery

        <action name="Pager" class="ActionPackage.PageAction" method="Pager">
                <result type="json">  
                <!-- 這裏指定將被Struts2序列化的屬性,該屬性在action中必須有對應的getter方法 -->  
                <param name="root1">userList</param>  
            </result> 
        </action>
        <action name="Init" class="ActionPackage.PageAction" method="Init">
             <result type="json">  
                <!-- 這裏指定將被Struts2序列化的屬性,該屬性在action中必須有對應的getter方法 -->  
                <param name="root">dataMap</param>  
            </result>  
        </action>

  主要難題:json對象的解析。由於前端代碼不是很熟悉,查了不少資料,傳回來的數據是Object Object類型的,其實用for循環加上k,v訪問就ok了。最後記錄動態表格生成的代碼。ajax

    var table = $('#content');
    table.html("");
    var thead = $("<tr></tr>");
    thead.appendTo(table);
    var tagName = $("<td>id</td>");
    tagName.appendTo(thead);
    tagName = $("<td>name</td>");
    tagName.appendTo(thead);
    tagName = $("<td>sex</td>");
    tagName.appendTo(thead);
    tagName = $("<td>age</td>");
    tagName.appendTo(thead);

  效果圖:apache

  

相關文章
相關標籤/搜索