【问题标题】:pagination not working in data-tables , showing all records at a time?分页在数据表中不起作用,一次显示所有记录?
【发布时间】:2017-01-25 05:41:11
【问题描述】:

几天以来,我一直在使用 data-table 。一切都很好,只是分页不能正常工作。enter image description here

我使用下面的代码从数据库中获取数据-

$data = array();
while( $row=mysqli_fetch_array($query) ) {  // preparing an array
    $nestedData=array();        
    $nestedData[] = $row["category"];
    $nestedData[] = $row["itemValue"];
    $nestedData[] = $row["quantity"];
    $nestedData[] = $row["location"];
    $nestedData[] = $row["comment"];
    $nestedData['file'] = $row["file"];
    $nestedData['itemId'] = $row["itemId"];
    $data[] = $nestedData;
}



$json_data = array(
            "draw" => intval( $requestData['draw'] ),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. 
            // "totalFiltered"    => intval( $totalData ),  // total number of records
            "recordsTotal"  => intval( $totalData ),  // total number of records
            "recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
            "aaData" => $data  // total data array
            );

echo json_encode($json_data); 

对于数据表 API,使用了以下-

var table = $('#example').DataTable( {
    "serverSide": true,
    "bProcessing": true,
    "paging": true,        
    "Filter": true,
    "ajax": {
            url:"select.php",
            type:"post",
        },        
    "rowId":'itemId',
    "file":'file',
    // "pagingType": "simple_numbers",
    "columnDefs": [ {
        "targets": -1,
         // "data": data,
        "defaultContent": "<div class='btn-group'><button type='button'  class='viewItem btn btn-success'><span class='glyphicon glyphicon-eye-open' aria-hidden='false'></span></button><button type='button'  class='editItem btn btn-success'><span class='glyphicon glyphicon-pencil' aria-hidden='false'></span></button></div>"
    } ]

});

在您可以看到的图像中,即使分页长度为 10,但它一次显示所有记录,即使我单击分页按钮,它也不会更改数据表中的行。请那里的任何人建议?谢谢

【问题讨论】:

  • 在这里粘贴你的代码

标签: jquery pagination datatables


【解决方案1】:

我想解释奥马尔的答案,并希望这对其他人特别是初学者有益。

如果您将数据从服务器发送到 DataTable 并期望它会根据您在 Datatable 声明中定义的设置自动对您的记录进行分页,那么您错了。您必须在服务器端编写分页功能。每当您单击 Datatable 的“NEXT”按钮时,它将调用服务器代码(Web 服务、方法等)并发送一个参数列表,您可以使用这些参数列表非常轻松地实现分页。

请仔细阅读本文,您可以很容易地在您使用的任何技术中实现这一点。

以下是使用 DataTable 正确实现分页所需遵循的步骤。

真的很简单很容易,只要注意。

我正在使用 DataTable、Spring MVC、Spring REST 和 Hibernate。

JavaScript 代码

    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
    <script src= "https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src= "https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#example').DataTable( {
                "processing": true,
                "serverSide": true,
                "paging":true,
                "ajax": "rest/getQuestions",
                "columns": [
                    { "data": "id" },
                    { "data": "name" },
                    { "data": "city" },
                    { "data": "country" },
                    { "data": "date" },
                    { "data": "email" },
                    { "data": "subject" },
                    { "data": "question" },
                    { "data": "status" },
                    { "data": "views" },
                    { "data": "submittedBy" }
                ]
            } );
        } );
    </script>
</head>

rest/getQuestions 是 WebService 调用。我的表的名称是 Question_tbl,我正在显示我的表的所有列。

HTML 表格

        <table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th> ID </th>
                <th> Name </th>
                <th> City </th>
                <th> Country </th>
                <th> Date </th>
                <th> Email </th>
                <th> Subject </th>
                <th> Question </th>
                <th> Status </th>
                <th> Views </th>
                <th> Submitted By </th>
            </tr>
        </thead>

    </table>   

Spring 休息服务

    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.web.bind.annotation.RequestParam;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.JsonMappingException;

    @RequestMapping(value = "/rest/getQuestions", method = RequestMethod.GET)
    public String getPaginatedQuestions(@RequestParam Integer draw, @RequestParam Integer start, @RequestParam Integer length ) {

    List<Question_tbl> paginatedQuestions = questionService.getPaginatedQuestionsSrv(start, length);       
    int questionCount = questionService.getQuestionCountByLimit(300);
    QuestionDataTable dt = new QuestionDataTable();

    dt.setDraw(draw);
    dt.setRecordsTotal(questionCount);
    dt.setRecordsFiltered(questionCount);
    dt.setData(paginatedQuestions);

    ObjectMapper mapper = new ObjectMapper();
    try {
        String jsonGenerated = mapper.writeValueAsString(dt);
        return jsonGenerated;
    } catch (JsonProcessingException ex) {
        Logger.getLogger(QuestionRestController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return new JsonMappingException("Exception").toString();

    }

Question_tbl 是我的实体表,它映射到数据库表名称Question。 3个请求参数draw、start、length从Datatable发送到服务器。

还有其他参数,我在下面展示了,但这些足以实现分页。将它们发送到服务层以获取分页记录。在数据库层,你只需要简单地实现下面的代码,你就会得到需要的记录。

DAO 方法

    public List<Question_tbl> getPaginatedQuestionsDao(int start, int length){

    Query qry = sessionFactory.getCurrentSession().createQuery("from Question_tbl q ORDER BY q.date DESC");
    qry.setFirstResult(start);
    qry.setMaxResults(length);
    return qry.list();
    }

什么是QuestionDataTable及其用途

要获取 Json 格式的数据,我们有一个 RestService。调用 RestService 时,从服务调用返回的结果 json 不是 DataTable 所需的格式。所以我们需要处理返回的 JSON 以正确显示 DataTable 中的数据。返回的实际 JSON 是这样的

      {
      "id": 10,
      "name": "Muhammad.s",
      "city": "Lahore",
      "country": "Pakistan",
      "date": 1491549259000,
      "email": "emil@email.com",
      "subject": "Testing Subject",
      "question": "Test Question-1",
      "status": "unanswered",
      "views": 0,
      "submittedBy": null
    },
    {
      "id": 8,
      "name": "Tariq.s",
      "city": "Hyderabad",
      "country": "Pakistan",
      "date": 1490465223000,
      "email": "abc@gmail.com",
      "subject": "Subject 2",
      "question": "Test question",
      "status": "unanswered",
      "views": 0,
      "submittedBy": null
    }

但 DataTable 所需的格式应该有 3 个初始元素,分别是 "draw""recordsTotal""recordsFiltered"。有关 JSON 格式的进一步说明,请查看此 link。这是所需且正确的格式。

{
  "draw": 9,
  "recordsTotal": 12,
  "recordsFiltered": 12,
  "data": [
    {
      "id": 12,
      "name": "Qalb-E-Muhammadi",
      "city": "Oval",
      "country": "England",
      "date": 1491550466000,
      "email": "email@gmail.com",
      "subject": "Test Subject 1",
      "question": "Test Question",
      "status": "unanswered",
      "views": 0,
      "submittedBy": null
    },
    {
      "id": 11,
      "name": "Buzjani",
      "city": "Sydney",
      "country": "Australia",
      "date": 1491549438000,
      "email": "email@email.com",
      "subject": "Testing Subject",
      "question": "Testing Question",
      "status": "unanswered",
      "views": 0,
      "submittedBy": null
    }
  ]
}

为此,我创建了名为 “QuestionDataTable” 的实用程序类。

public class QuestionDataTable {
    private int draw;
    private int recordsTotal;
    private int recordsFiltered;
    private List<Question_tbl> data;
    // Getters, Setters
}

然后我通过上面定义的 Rest 服务中定义的 ObjectMapper 类将 QuestionDataTable 对象转换为 Json。

从DataTable返回给Web Service的请求参数

draw:1
columns[0][data]:firstName
columns[0][name]:
columns[0][searchable]:true
columns[0][orderable]:true
columns[0][search][value]:
columns[0][search][regex]:false
columns[1][data]:lastName
columns[1][name]:
columns[1][searchable]:true
columns[1][orderable]:true
columns[1][search][value]:
columns[1][search][regex]:false
columns[2][data]:age
columns[2][name]:
columns[2][searchable]:true
columns[2][orderable]:true
columns[2][search][value]:
columns[2][search][regex]:false
order[0][column]:0
order[0][dir]:asc
start:0
length:10
search[value]:
search[regex]:false

您可以在调用 Rest Service 后在浏览器中查看请求的 HEAD 部分中发送的上述参数。图片为chrome示例Chrome example

我知道这是一篇很长的帖子,我已尽力涵盖所有相关方面,这样您就不必在这里跳来跳去。我希望这将节省您寻找相关解决方案的宝贵时间。

【讨论】:

    【解决方案2】:
    // You missing to put query code , anyway see the below example 
    $sql="SELECT * FROM table WHERE category = '$code' ";
    $query_count=mysql_query($sql);
    
    $per_page =30;//define how many games for a page
    $count = mysql_num_rows($query_count);
    $pages = ceil($count/$per_page);
    
    if($_GET['page']==""){
    $page="1";
    }else{
    $page=$_GET['page'];
    }
    $start    = ($page - 1) * $per_page;
    $sql     = $sql." LIMIT $start,$per_page";
    $query2=mysql_query($sql);
    
    // Hope you can find your solution here
    

    【讨论】:

    • it didn't work 是什么意思?基本上问题是您没有处理查询中的分页,这就是答案所展示的。这不是您问题的确切答案,即您不能只是复制/粘贴并期望它起作用。您必须根据自己的情况进行调整。
    • 是的,这不是这个问题的确切答案,它只是一个例子。您必须了解代码并从中获取一些知识。 :)
    猜你喜欢
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 2023-03-15
    • 2019-10-31
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多