分页,ajax。

本文介绍了如何使用Ajax技术实现父页面中输入开始和结束日期后,通过AJAX请求调用后台接口查询并显示登录日志详情,并实现了分页功能,确保了数据的高效展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

父页面jsp的代码如下,其中核心是getDate这个js方法,中间一段业务不用看,核心代码在于使用ajax技术实现的获取数据并将其显示于一个子页面的过程,就是下面这两个js方法:

function queryReport() {
        var startDate = jQuery.trim(jQuery("#startDate").val());
        var endDate = jQuery.trim(jQuery("#endDate").val());
        getData(startDate, endDate, 20, 1);
    }


function getData(startDate, endDate, numOfPage, pageNum) {
  jQuery.ajaxSetup({
            cache : false
        });      

 jQuery.get("${ctx}/queryLoginCount.action", {
                            startDate : startDate,
                            endDate : endDate,
                            numOfPage : numOfPage,
                            pageNum : pageNum
                        }, function(data) {
                            jQuery("#reportDiv").html(data);
                        });
    }


下面是整个父页面jsp的代码:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<%
    response.addHeader(
            "P3P",
            "CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登录日志详情</title>
<link rel="stylesheet" href="${ctx }/css/base/jquery.ui.all.css">
<link rel="stylesheet" href="${ctx }/css/common.css">
<script src="${ctx}/js/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="${ctx}/js/jquery-ui-1.8.15.custom.min.js"
    type="text/javascript"></script>
<script type="text/javascript" src="${ctx}/js/WdatePicker.js"></script>
<script type="text/javascript">
    Date.prototype.format = function(format) {
        var o = {
            "M+" : this.getMonth() + 1, //month
            "d+" : this.getDate(), //day
            "h+" : this.getHours(), //hour
            "m+" : this.getMinutes(), //minute
            "s+" : this.getSeconds(), //second
            "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
            "S" : this.getMilliseconds() //millisecond
        };
        if (/(y+)/.test(format))
            format = format.replace(RegExp.$1, (this.getFullYear() + "")
                    .substr(4 - RegExp.$1.length));
        for ( var k in o)
            if (new RegExp("(" + k + ")").test(format))
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                        : ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    };

    function queryReport() {
        var startDate = jQuery.trim(jQuery("#startDate").val());
        var endDate = jQuery.trim(jQuery("#endDate").val());
        getData(startDate, endDate, 20, 1);
    }

    function getData(startDate, endDate, numOfPage, pageNum) {
        jQuery.ajaxSetup({
            cache : false
        });
        var date_start = new Date();
        var date_end = new Date();
        var thisTime = 14 * 24 * 60 * 60 * 1000;
        date_start.setFullYear(startDate.substring(0, 4));
        date_start.setMonth(startDate.substring(5, 7));
        date_start.setDate(startDate.substring(8, 10));
        date_end.setFullYear(endDate.substring(0, 4));
        date_end.setMonth(endDate.substring(5, 7));
        date_end.setDate(endDate.substring(8, 10));

        if (startDate != null && startDate != '') {
            if (endDate != null && endDate != '') {
                if (startDate > endDate) {
                    alert('起始日期已经大于截止日期!');
                } else {
                    if ((date_end - date_start) <= thisTime) {
                        jQuery.get("${ctx}/queryLoginCount.action", {
                            startDate : startDate,
                            endDate : endDate,
                            numOfPage : numOfPage,
                            pageNum : pageNum
                        }, function(data) {
                            jQuery("#reportDiv").html(data);
                        });
                    } else {
                        alert("请查询两周内的数据!");
                    }
                }
            } else {
                date_start = new Date(date_start.getFullYear(), date_start
                        .getMonth() - 1, date_start.getDate());
                date_end = new Date(date_start.getFullYear(), date_start
                        .getMonth(), date_start.getDate() + 14);
                date_start = date_start.format('yyyy-MM-dd');
                date_end = date_end.format('yyyy-MM-dd');
                jQuery.get("${ctx}/queryLoginCount.action", {
                    startDate : date_start,
                    endDate : date_end,
                    numOfPage : numOfPage,
                    pageNum : pageNum
                }, function(data) {
                    jQuery("#reportDiv").html(data);
                });
            }
        } else {
            if (endDate != null && endDate != '') {
                date_end = new Date(date_end.getFullYear(),
                        date_end.getMonth() - 1, date_end.getDate());
                date_start = new Date(date_end.getFullYear(), date_end
                        .getMonth(), date_end.getDate() - 14);
                date_end = date_end.format('yyyy-MM-dd');
                date_start = date_start.format('yyyy-MM-dd');
                jQuery.get("${ctx}/queryLoginCount.action", {
                    startDate : date_start,
                    endDate : date_end,
                    numOfPage : numOfPage,
                    pageNum : pageNum
                }, function(data) {
                    jQuery("#reportDiv").html(data);
                });
            } else {
                var date_start = new Date();
                var date_end = new Date();
                date_start = new Date(date_start.getFullYear(), date_start
                        .getMonth(), date_start.getDate() - 14);
                date_start = date_start.format('yyyy-MM-dd');
                date_end = date_end.format('yyyy-MM-dd');
                jQuery.get("${ctx}/queryLoginCount.action", {
                    startDate : date_start,
                    endDate : date_end,
                    numOfPage : numOfPage,
                    pageNum : pageNum
                }, function(data) {
                    jQuery("#reportDiv").html(data);
                });
            }
        }
    }
</script>
</head>
<body>
    <table id="inputTable" width="100%" border="1" align="center"
        class="add_table">
        <tr>
            <td width="30%" class="addtable_left"><label>统计时间:</label></td>
            <td align="left" width="40%" class="tdright"><input
                id="startDate" name="startDate" class="Wdate" type="text"
                onClick="WdatePicker()" value="${startDate}" class="text">—<input
                id="endDate" name="endDate" class="Wdate" type="text"
                onClick="WdatePicker()" value="${endDate}" class="text"></td>

            <td colspan="4"><input value="查询" onclick="queryReport()"
                type="button" class="right-button02"></td>

        </tr>
    </table>
    <div id="reportDiv" style="overflow: auto; height: 300px;"></div>
</body>
<script type="text/javascript">
    $(function() {
        var frame = jQuery(window.parent.document).find("iframe")[0];
        var frameHeight = jQuery(frame).height();
        var inputTableHeight = jQuery("#inputTable").height();
        jQuery("#reportDiv").css({
            height : frameHeight - inputTableHeight - 20
        });
        //当窗口缩放时以上两种情况自适应
        window.onresize = function() {
            var frame = jQuery(window.parent.document).find("iframe")[0];
            var frameHeight = jQuery(frame).height();
            var inputTableHeight = jQuery("#inputTable").height();
            jQuery("#reportDiv").css({
                height : frameHeight - inputTableHeight - 20
            });
        };
    });
</script>
</html>

然后子页面有分页的实现:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
    response.addHeader(
            "P3P",
            "CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>次数统计</title>
<link rel="stylesheet" href="${ctx }/css/base/jquery.ui.all.css">
<link rel="stylesheet" href="${ctx }/css/common.css">
<script src="${ctx}/js/swfobject.js" type="text/javascript"></script>
<script src="${ctx}/js/json2.js" type="text/javascript"></script>
<script src="${ctx}/js/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="${ctx}/js/jquery.scrollLoading-min.js" type="text/javascript"></script>
<script type="text/javascript">
function openLoginResultInfoWindow(LOG_DATE){
    window.open('${ctx}/queryLoginCountInfo.action?logDate='+LOG_DATE, 'newwindow', 'height=400, width=600, top=100, left=300, toolbar=no, menubar=no, scrollbars=no, resizable=yes,location=no, status=no');
}
var url="${ctx}/countBarChart.action?startDate=${startDate}&endDate=${endDate}";

url=encodeURI(url);
url=url.replace(/&/g,'%26').toString();
swfobject.embedSWF("<s:url value="/js/open-flash-chart.swf"/>", "my_chart", "98%", "300", "9.0.0",
            "<s:url value="/js/expressInstall.swf"/>",
            {"data-file":url},
            {wmode:"transparent"});    

function firstPage() {
    getData('${startDate}', '${endDate}', 20, 1);
    
}
//上一页
function lastPage() {
    getData('${startDate}', '${endDate}', 20,
            '${pageNum-1}');
    
}
//下一页
function nextPage() {
    getData('${startDate}', '${endDate}', 20,
            '${pageNum+1}');
    
}
//末页
function endPage() {
    getData('${startDate}', '${endDate}', 20,
            '${pageCount}');
        
}
</script>

<style type="text/css">
.href_btn {
    cursor: pointer;
    color: blue;
    text-decoration: underline
}
</style>
</head>

<table width="98%" border="0" cellpadding="0" cellspacing="0"
        align="center">
        <tr>
            <td align="center">
                <table width="100%" class="edit_table"  style="margin:0 0 0 0;padding:0 0 0 0;" cellpadding="0" cellspacing="0"
                    align="center">
                    <tr>
                        <td>
                            <div id="my_chart"></div></td>
                        
                    </tr>
                    
                </table></td>
        </tr>
        <tr>
            <td align="center">&nbsp;</td>
        </tr>
</table>        
<table id="resultTable" class="edit_table" cellpadding="4"
    cellspacing="1">
    <c:if test="${loginCountList!=null}">
        <tr style="background: #eee;">
            <th style="width: 10%">时间</th>
            <th style="width: 10%">登录人数</th>
            <th style="width: 10%">登录次数</th>
            <th style="width: 10%">详情</th>
        </tr>
        
        <c:forEach items="${loginCountList}" varStatus="v" var="k">
            <tr style="background: #fff;">
                <td><c:out value="${k.LOG_DATE}" /></td>
                <td><c:out value="${k.USER_CNT}" /></td>
                <td><c:out value="${k.LOGIN_CNT}" /></td>
                <td><a onclick="openLoginResultInfoWindow('${k.LOG_DATE}')"
                    style="cursor: pointer; color: blue;">查看</a></td>
            </tr>
        </c:forEach>
    </c:if>
    
    <tr>
        <td colspan="4" align="right">
            共<c:out value="${totalCount1}" />条 每页<c:out value="${numOfPage}" />条
            共<c:out value="${pageCount}" />页 当前第<c:out value="${pageNum}" />页
            <c:if test="${pageNum>1}">
                <a onclick="firstPage();" style="cursor: pointer; color: blue;">首页</a>
            </c:if>
            <c:if test="${pageNum>1}">
                <a onclick="lastPage();" style="cursor: pointer; color: blue;">上一页</a>
            </c:if>
            <c:if test="${pageNum<pageCount}">
                <a onclick="nextPage();" style="cursor: pointer; color: blue;">下一页</a>
            </c:if>
            <c:if test="${pageNum<pageCount}">
                <a onclick="endPage();" style="cursor: pointer; color: blue;">末页</a>
            </c:if>
        </td>
    </tr>
</table>

逻辑写在action里面,有一个方法:

public String queryLoginLog() {
        userName = "%" + userName + "%" ;
        if (pageNum == 0) {
            pageNum = 1;
        }
        int startRow = new Integer((pageNum - 1) * numOfPage + 1);
        int endRow = new Integer(pageNum * numOfPage);
        countList = loginLogService.queryLoginLogCount(userName, startDate, endDate);
        totalCount = Integer.parseInt(countList.get(0).get("TOTALCOUNT").toString());
        this.loginLogList = loginLogService.queryLoginLog(userName, startRow, endRow, startDate, endDate);
        setPageCount((totalCount-1)/numOfPage+1);
        return "success";
    }


<think>好的,我现在需要解决用户的问题,关于如何在JavaScript中使用Datatables插件通过Ajax实现分页功能。首先,我要回忆一下DataTables的基本用法,特别是Ajax模式下的配置。记得用户提到的引用[1]中提到了在Ajax模式下,服务器需要处理请求并返回JSON数据,所以关键点应该在于配置DataTables的Ajax选项,以及服务器端的处理。 接下来,我应该分步骤来回答。第一步,确保用户已经正确引入了jQuery和DataTables的相关文件,这是基础。然后,创建一个表格的HTML结构,指定thead和tbody,但tbody可以为空,因为数据会通过Ajax加载。 然后,JavaScript的初始化部分。DataTables的配置中,需要设置processing和serverSide为true,这样插件会显示处理中的提示,并启用服务器端分页Ajax选项需要指定请求的URL,可能还需要配置dataSrc来正确解析服务器返回的数据格式。比如,如果服务器返回的是data数组,可能需要设置dataSrc: 'data'。 接下来是columns的配置,这部分需要和服务器返回的JSON数据的字段对应,确保每一列都能正确显示数据。此外,如果服务器需要额外的参数,比如每页的数量或当前页码,可能需要通过ajax.data回调函数来添加这些参数。 然后,服务器端的处理也是关键。根据引用[1],服务器需要接收DataTables发送的参数,如draw、start、length等,进行数据查询、过滤、排序和分页,然后按照特定的JSON格式返回,包括draw、recordsTotal、recordsFiltered和data数组。用户可能需要根据他们使用的后端语言(比如PHP、Node.js等)来实现这部分逻辑。 最后,生成相关问题的时候,应该围绕DataTables的其他功能、参数处理、性能优化和与其他技术的结合来提问,帮助用户进一步学习。 现在需要检查是否有遗漏的步骤,比如分页样式的配置,或者错误处理。另外,确保示例代码中的URL和后端处理部分有注释说明,让用户知道需要替换成自己的接口。可能还需要提到draw参数的作用,用于防止CSRF攻击或者确保请求和响应对应。 总结一下,回答的结构应该是先介绍基本步骤,然后给出示例代码,解释关键配置项,最后说明服务器端的要求,并附上相关问题。同时,引用中的内容要自然地融入回答中,比如引用[1]关于服务器处理的部分。</think>以下是如何在JavaScript中使用DataTables插件通过AjAX实现分页功能的详细步骤: ### 一、基础实现步骤 1. **引入依赖库** ```html <!-- jQuery与DataTables核心库 --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.css"> <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.js"></script> ``` 2. **创建表格结构** ```html <table id="example" class="display"> <thead> <tr> <th>ID</th> <th>名称</th> <th>创建时间</th> </tr> </thead> </table> ``` 3. **初始化DataTables配置** ```javascript $(document).ready(function() { $('#example').DataTable({ processing: true, // 显示处理提示 serverSide: true, // 启用服务器模式[^1] ajax: { url: '/api/data', type: 'POST', dataSrc: 'data' // 指定数据源路径 }, columns: [ { data: 'id' }, { data: 'name' }, { data: 'create_time' } ] }); }); ``` ### 二、服务器端要求 根据DataTables协议,服务器需要处理以下关键参数: | 参数 | 描述 | 示例值 | |------------|---------------------|-------| | draw | 请求计数器 | 1 | | start | 起始记录索引 | 0 | | length | 每页记录数 | 10 | | search[value] | 全局搜索关键词 | "test" | 响应格式要求: ```json { "draw": 1, "recordsTotal": 100, "recordsFiltered": 35, "data": [ { "id": 1, "name": "示例数据", "create_time": "2023-10-01" } ] } ``` ### 三、高级配置示例 ```javascript ajax: { url: '/api/custom', data: function(d) { // 添加额外参数 d.custom_filter = $('#filter').val(); } }, columnDefs: [{ targets: 0, render: function(data) { return `<span class="badge">${data}</span>`; } }] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值