ajax分页查询信息的通用方法

1.页面准备分页的表格与分页div

  同时需要在查询条件表单中准备隐藏当前页与页大小的文本框

            <div class="container-fluid">
                <div class="panel panel-default">
                    <!--菜单连接标题-->
                    <div class="panel-heading">
                        <span>大修管理</span><span>>大修信息管理</span>
                    </div>

                    <div class="el_main">

                        <!--内容-->
                        <div class="el_qlmContent">

                            <!--索引-->
                            <div class="row el_queryBox">
                                <form id="haulQueryForm">
                                    <!--隐藏当前页与页大小  -->
                                    <input type="hidden" name="currentPage" id="currentPage">
                                    <input type="hidden" name="currentCount" id="currentCount">

                                    <div class="row">

                                        <div class="col-md-3 el_qlmQuery">
                                            <div class="input-group" role="toolbar">
                                                <span class="el_spans">大修名称:</span> <input type="text"
                                                    class="form-control" name="bigName" />
                                            </div>
                                        </div>

                                        <div class="col-md-3 el_qlmQuery">
                                            <div class="input-group" role="toolbar">
                                                <span class="el_spans">大修时间:</span> <input type="text"
                                                    name="startMonth" id="test" class="wicon form-control"
                                                    readonly />
                                            </div>
                                        </div>

                                        <div class="col-md-3 el_qlmQuery">
                                            <div class="input-group" role="toolbar">
                                                <span class="el_spans">大修状态:</span> <select
                                                    class="selectpicker form-control" name="bigStatus"
                                                    title="请选择">
                                                    <option value="">--请选择--</option>
                                                    <option value="未开始">未开始</option>
                                                    <option value="进行中">进行中</option>
                                                    <option value="已结束">已结束</option>
                                                </select>
                                            </div>
                                        </div>

                                    </div>


                                    <!--提交查询按钮-->
                                    <button type="reset"
                                        class="btn btn-default el_queryButton0 btn-sm">清空</button>
                                    <button type="button" id="haulQueryButton"
                                        class="btn btn-default el_queryButton btn-sm">查询</button>
                                </form>

                            </div>
                            <!--结束 查询表单提交-->

                            <!--显示内容-->
                            <h4 class="el_mainHead">大修信息</h4>
                            <div class="panel panel-default el_Mainmain">

                                <!--按钮面板-->
                                <div class="panel-body">

                                    <div class="panel panel-default">
                                        <div class="panel-body el_MainxiaoMain">

                                            <div class="el_topButton">
                                                <button class="btn btn-primary" onclick="el_addOverhaul()">
                                                    创建大修</button>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 表格 内容都提取到json里边 -->
                                    <table class="table table-hover table-bordered" id="newsTable">
                                        <thead>
                                            <tr>
                                                <th>序号</th>
                                                <th>大修名称</th>
                                                <th>时间</th>
                                                <th>状态</th>
                                                <th width="350">操作</th>
                                            </tr>
                                        </thead>
                                        <tbody id="haulTbody">
                                        </tbody>
                                    </table>

                                    <!--分页-->
                                    <div id="paginationIDU" class="paginationID"></div>
                                </div>
                            </div>

 

 2.JS代码:

  解释:点击查询的时候将页号清空(这个有时候容易忘),带着组合条件去后台查询,查询成功后将数据填充到表格之后显示分页组件。点击分页组件的页号与上下页的时候动态设置页面中隐藏域的值,同时调用查询方法。

/**
 * 页面初始化函数
 */
$(function() {
    // 页面初始化查询大修信息
    queryHaulFun();
    // 查询的点击事件
    $("#haulQueryButton").click(function() {
        $("#currentPage").val("");// 清空页数
        queryHaulFun();
    });

});
/** *S 分页查询大修信息*** */
// 查询大修
var queryHaulFun = function() {
    $.ajax({
        url : contextPath + "/findPageHaul.action",
        data : $("#haulQueryForm").serialize(),
        dataType : "JSON",
        async : true,
        type : "POST",
        success : showHaulTable,
        error : function() {
            alert("查询大修失败!!!");
        }

    });
}
// 显示大修分页信息到表格
function showHaulTable(response) {
    $("#haulTbody").html("");// 清空表格
    var haulinfos = response.pageBean.productList;// 获取到大修JSON对象
    var currentCount = response.pageBean.currentCount;// 页大小
    var totalCount = response.pageBean.totalCount;// 页总数
    var currentPage = response.pageBean.currentPage;// 当前页
    for (var i = 0, length_1 = haulinfos.length; i < length_1; i++) {
        // 填充表格
        $("#haulTbody")
                .append(
                        '<tr><td>'
                                + (parseInt(currentCount)
                                        * parseInt(currentPage - 1) + (i + 1))
                                + '</td><td>'
                                + haulinfos[i].bigname
                                + '</td><td>'
                                + haulinfos[i].bigbegindate
                                + '  到  '
                                + haulinfos[i].bigenddate
                                + '</td><td>'
                                + haulinfos[i].bigstatus
                                + '</td><td>'
                                + '<a href="<%=path%>/view/overhaul/overhaulInfo.jsp">详情</a>'
                                + '<a href="javascript:void(0)" οnclick="el_modifyOverhaul()">修改</a>'
                                + '<a href="javascript:void(0)" οnclick="delcfmOverhaul()">删除</a>'
                                + '</td></tr>');
    }
    // 动态开启分页组件
    page(currentPage, totalCount, currentCount);
}
// 显示分页
function page(currentPage, totalCount, currentCount) {
    // 修改分页的基本属性
    $('#paginationIDU').pagination(
            {
                // 组件属性
                "total" : totalCount,// 数字 当分页建立时设置记录的总数量 1
                "pageSize" : currentCount,// 数字 每一页显示的数量 10
                "pageNumber" : currentPage,// 数字 当分页建立时,显示的页数 1
                "pageList" : [ 8 ],// 数组 用户可以修改每一页的大小,
                // 功能
                "layout" : [ 'list', 'sep', 'first', 'prev', 'manual', 'next',
                        'last', 'links' ],
                "onSelectPage" : function(pageNumber, pageSize) {
                    $("#currentPage").val(pageNumber);
                    $("#currentCount").val(pageSize);
                    // 查询大修
                    queryHaulFun();
                }
            });
}
/** *E 分页查询大修信息*** */

 

 

 

 后台代码

工具类: PageBean.java

package cn.xm.exam.utils;

/**
 * 分页工具类
 */

import java.util.ArrayList;
import java.util.List;

public class PageBean<T> {

    // 当前页
    private int currentPage;
    // 当前页显示的条数
    private int currentCount;
    // 总条数
    private int totalCount;
    // 总页数
    private int totalPage;
    // 每页显示的数据
    private List<T> productList = new ArrayList<T>();

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getCurrentCount() {
        return currentCount;
    }

    public void setCurrentCount(int currentCount) {
        this.currentCount = currentCount;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public List<T> getProductList() {
        return productList;
    }

    public void setProductList(List<T> productList) {
        this.productList = productList;
    }

    @Override
    public String toString() {
        return "PageBean [currentPage=" + currentPage + ", currentCount=" + currentCount + ", totalCount=" + totalCount
                + ", totalPage=" + totalPage + ", productList=" + productList + "]";
    }

}

 

3.Action代码:

  首先组装查询条件(对数据进行初始化处理),调用service层进行查询,返回的索引信息都封装在pageBean对象中,将PageBean装入map中转为JSON传到前台。

package cn.xm.exam.action.haul;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;

import cn.xm.exam.bean.haul.Haulinfo;
import cn.xm.exam.service.haul.HaulinfoService;
import cn.xm.exam.utils.PageBean;
import cn.xm.exam.utils.ValidateCheck;

/**
 * 查询大修的Action
 * 
 * @author QiaoLiQiang
 * @time 2017年11月10日下午7:45:09
 */
@Controller
@Scope("prototype")
@SuppressWarnings("all")
public class FindHaulAction extends ActionSupport {
    private Logger logger = Logger.getLogger(FindHaulAction.class);// 日志记录器
    private Map<String, Object> response;// 用于包装返回结果的map
    @Resource
    private HaulinfoService haulinfoService;
    private String currentPage;// 当前页
    private String currentCount;// 页大小
    private String bigName;// 大修名称
    private String bigStatus;// 大修状态
    private String startMonth;// 创建月份

    @Override
    public String execute() {
        response = new HashMap<String, Object>();
        Map<String, Object> condition = generateQueryHaulCondition();
        PageBean<Haulinfo> pageBean = null;
        try {
            pageBean = haulinfoService.getHaulinfoPageByCondition(Integer.valueOf(currentPage),
                    Integer.valueOf(currentCount), condition);
        } catch (NumberFormatException e) {
            logger.error("数字格式化异常", e);
        } catch (SQLException e) {
            logger.error("查询大修SQL异常", e);
        }
        response.put("pageBean", pageBean);
        return SUCCESS;
    }

    /**
     * 组装查询条件
     * 
     * @param condition
     * @return
     */
    private Map<String, Object> generateQueryHaulCondition() {
        Map<String, Object> condition = new HashMap<String, Object>();
        if (ValidateCheck.isNull(currentCount)) {
            currentCount = "8";
        }
        if (ValidateCheck.isNull(currentPage)) {
            currentPage = "1";
        }
        if (ValidateCheck.isNotNull(bigName)) {
            condition.put("bigName", bigName);
        }
        if (ValidateCheck.isNotNull(bigStatus)) {
            condition.put("bigStatus", bigStatus);
        }
        if (ValidateCheck.isNotNull(startMonth)) {
            condition.put("startMonth", startMonth);
        }
        return condition;
    }

    // get set
    public Map<String, Object> getResponse() {
        return response;
    }

    public void setResponse(Map<String, Object> response) {
        this.response = response;
    }

    public String getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(String currentPage) {
        this.currentPage = currentPage;
    }

    public String getCurrentCount() {
        return currentCount;
    }

    public void setCurrentCount(String currentCount) {
        this.currentCount = currentCount;
    }

    public String getBigName() {
        return bigName;
    }

    public void setBigName(String bigName) {
        this.bigName = bigName;
    }

    public String getBigStatus() {
        return bigStatus;
    }

    public void setBigStatus(String bigStatus) {
        this.bigStatus = bigStatus;
    }

    public String getStartMonth() {
        return startMonth;
    }

    public void setStartMonth(String startMonth) {
        this.startMonth = startMonth;
    }

}

 

 

 4.Service层代码:

    将当前页,页大小,页总数,总记录数,数据集合装入PageBean返回给Action。(满足条件的总数需要根据条件查出,之后计算出总页数,并根据当前页与页大小计算起始值并装入条件map中传到mapper层查询数据集合)

@Override
    public PageBean<Haulinfo> getHaulinfoPageByCondition(int currentPage, int currentCount,
            Map<String, Object> condition) throws SQLException {
        PageBean<Haulinfo> pageBean = new PageBean<Haulinfo>();
        pageBean.setCurrentCount(currentCount);// 设置页大小
        pageBean.setCurrentPage(currentPage);// 设置当前页
        int total = 0;
        int totalCount = haulinfoCustomMapper.getHaulinfoTotalByCondition(condition);// 查询满足条件的总数
        pageBean.setTotalCount(totalCount);// 设置总记录数
        int totalPage = (int) Math.ceil(1.0 * totalCount / currentCount);
        pageBean.setTotalPage(totalPage);// 设置总页数

        /******
         * 计算起始值
         *  页数 起始值 页大小
         *  1 0 8 
         *  2 8 16
         *******/
        int index = (currentPage - 1) * currentCount;// 起始值
        condition.put("index", index);
        condition.put("currentCount", currentCount);
        List<Haulinfo> haulinfos = haulinfoCustomMapper.getHaulinfoslByCondition(condition);
        pageBean.setProductList(haulinfos);//设置数据集合
        return pageBean;
    }

 

 

5.Mapper层代码

  mapper接口:

package cn.xm.exam.mapper.haul.custom;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import cn.xm.exam.bean.haul.Haulinfo;

/**
 * 大修基本信息mapper
 * 
 * @author QiaoLiQiang
 * @time 2017年11月10日下午12:23:15
 */
public interface HaulinfoCustomMapper {

    /**
     * 查询满足条件的大修总数
     * 
     * @param condition
     *            条件
     * @return
     * @throws SQLException
     */
    public int getHaulinfoTotalByCondition(Map<String, Object> condition) throws SQLException;

    /**
     * 组合条件查询大修信息用于分页显示大修
     * 
     * @param condition
     * @return
     * @throws SQLException
     */
    public List<Haulinfo> getHaulinfoslByCondition(Map<String, Object> condition) throws SQLException;
}

 

 

mapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.xm.exam.mapper.haul.custom.HaulinfoCustomMapper">

    <!--S 查询分页总数 -->
    <select id="getHaulinfoTotalByCondition" parameterType="hashmap"
        resultType="_int">
        SELECT
        COUNT(bigId) FROM haulinfo
        <where>
            <include refid="queryHaulWhere"></include>
        </where>
    </select>
    <!--E 查询分页总数 -->
    <!--S 分页查询大修 -->
    <select id="getHaulinfoslByCondition" resultType="cn.xm.exam.bean.haul.Haulinfo"
        parameterType="hashmap">
        SELECT * FROM haulinfo
        <where>
            <include refid="queryHaulWhere"></include>
        </where>
        <include refid="queryHaulLimit"></include>
    </select>
    <!--E 分页查询大修 -->




    <!--S 组装查询条件 -->
    <sql id="queryHaulWhere">
        <if test="bigName!=null">
            and bigName LIKE '%${bigName}%'
        </if>
        <if test="bigStatus!=null">
            and bigStatus=#{bigStatus}
        </if>
        <if test="startMonth!=null">
            and DATE_FORMAT(bigCreateDate,'%Y-%m')=#{startMonth}
        </if>
    </sql>
    <!--E 组装查询条件 -->
    <!--S 分页条件 -->
    <sql id="queryHaulLimit">
        <if test="index!=null">
            LIMIT #{index},#{currentCount}
        </if>
    </sql>
    <!--E 组装分页条件 -->




</mapper>

 

 

 

结果:

  后台传到前台的JSON:

 

   效果:

 

<div class="post-text" itemprop="text"> <p>我有一个 golang api,用于保存和检索表单中的数据。保存 HTML 表单中填充的数据是没问题的,它可以成功地将数据保存在 mongodb 的数据库中,在检索数据的情况下,它还将根据 html 表单字段中填写的电子邮件检索数据,但是它显示了 ubuntu 终端中的数据。下面是我正在尝试的代码:<p> <p>Html form index.html file</p> <pre><code><form id="form1" method="post"> <input id= "firstname" type="text" name="FirstName" placeholder="Enter your firstname"><br><br> <input id= "lastname" type="text" name="LastName" placeholder="Enter your lastname"><br><br> <input id= "email" type="text" name="Email" placeholder="Enter your email"><br><br> <input id= "mobile" type="text" name="Mobile" placeholder="Enter your mobile"><br><br> <button id= "button1" class="button" name="button" type="button" value="Submit">Submit</button> <button id= "button2" class="button" name="button" type="submit" value="Search">Search</button> </form> </code></pre> <p>Ajax in index.html is :-</p> <pre><code>$(document).ready(function(){ //IT will save the data $('#button1').on('click', function(e){ button=this.value; console.log(button); e.preventDefault(); if (button === "Submit") { var FirstName =$("#firstname").val(), LastName =$("#lastname").val(), Email =$("#email").val(), Mobile =$("#mobile").val(); console.log(FirstName); $.ajax({ url:"/login", type:"POST", data: {'button':button, "first":FirstName, "last":LastName, "email":Email, "mobile":Mobile}, success: function(results) { console.log(results); $('#response').html(results); } }); } }); // This will search and I want the result in the success $('#button2').on('click', function(e){ button=this.value; console.log(button); e.preventDefault(); var Email =$("#email").val(); $.ajax({ url:"/get-data", type: "GET", data:{'button':button,"email":Email}, success: function(results){ console.log(results) $('#response').html(results); } }); }); }); </code></pre> <p>Main.go file </p> <pre><code>import ( "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "html/template" "log" "net/http" "encoding/json" ) type USER struct { FirstName string `json:"FirstName,omitempty"` LastName string `json:"LastName,omitempty"` Email string `json:"Email,omitempty"` Mobile string `json:"Mobile,omitempty"` } func login(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) if r.Method == "GET" { t, _ := template.ParseFiles("index.html") t.Execute(w, nil) } else { r.ParseForm() fmt.Println(r.Form) if r.Form["button"][0] == "Submit" { fmt.Println(r.Form) session, err := mgo.Dial("mongodb://127.0.0.1:27017/user") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("user").C("profile") doc := USER{ FirstName: r.Form["first"][0], LastName: r.Form["last"][0], Email: r.Form["email"][0], Mobile: r.Form["mobile"][0], } err = c.Insert(doc) if err != nil { panic(err) } fmt.Println("FistName:", r.Form["first"][0]) fmt.Println("LastName:", r.Form["last"][0]) fmt.Println("Email:", r.Form["email"][0]) fmt.Println("Mobile:", r.Form["mobile"][0]) } } } func AllData(w http.ResponseWriter, r *http.Request){ fmt.Println("method:", r.Method) if r.Method == "GET" { r.ParseForm() fmt.Println(r.Form) if r.Form["button"][0] == "Search" { fmt.Println(r.Form) fmt.Println(r.Form["email"][0]) session, err := mgo.Dial("mongodb://127.0.0.1:27017/user") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("user").C("profile") result := Users{} err = c.Find(bson.M{"email": r.Form["email"][0]}).All(&result) fmt.Println(result) b, err := json.MarshalIndent(result, "", " ") if err != nil { panic(err) } fmt.Printf("%s ", b) } } } func main() { http.HandleFunc("/login", login) http.HandleFunc("/get-data", AllData) err := http.ListenAndServe(":9090", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } </code></pre> <p>用GET / code 方法请求数据时,我应该做什么,才能让结果成功显示在 ajax 函数中?先提前谢谢你。</p> </div>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页