分页不在数据表中工作,一次显示所有记录?

时间:2017-01-25 05:41:11

标签: jquery pagination datatables

因为几天我一直在使用数据表。一切都工作得很好,只是问题是分页不能很好地运作。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,但它一次显示所有记录,即使我点击分页按钮,它也不会更改数据表中的行。请有人建议吗?感谢

2 个答案:

答案 0 :(得分:0)

// 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

答案 1 :(得分:0)

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

如果您要从服务器向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>   

春季休息服务

    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 是我的实体表,它映射到数据库表名问题。 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 。这是必需的&amp;格式正确。

{
  "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”的util类。

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服务的请求参数

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呼叫后,您可以在Web浏览器中检查请求的HEAD部分中发送的上述参数。该图片为chrome示例Chrome example

我知道它的帖子很长,我尽力覆盖所有相关方面,这样你就不必跳到这里了。那里。我希望这可以节省你找到相关解决方案的宝贵时间。