ajax数据表:短/分页事件的POST过滤器参数


Ajaxed Datatable: POST filter parameters on shorting/pagination event

我已经实现了ajax Datatable,在一个分页表中表示大约5000行。

一切工作正常,直到过滤不应用。我可以短列& &;分页适用于未过滤的数据。

一旦,我在某些字段上应用short,假设我写了手机号码90331,那么它应该输出所有以90331开头的手机号码的记录,SQL按预期工作。搜索结果大约有2500行,根据分页设置,它给出前20行。但是只要我点击下一页按钮,它就会触发分页事件并发送没有"过滤参数"的ajax请求。因此,由于过滤参数不是在ajax请求上发送的,它不会过滤,它会丢失过滤的数据状态,并返回带有所有数据的第二页(没有过滤)。如果我点击列标题进行排序,也会发生同样的情况。

我如何使Datatable发送过滤参数值与事件排序&分页?

代码如下:

<table class="table table-striped table-bordered table-hover ajax-table">
    <thead>
        <tr role="row" class="heading">
            <th>Index</th>
            <th>Name</th>
            <th>Email</th>
            <th>Mobile</th>
            <th>Actions</th>
        </tr>
        <tr role="row" class="filter"> <!-- Custom filters here -->
            <td></td>
            <td>
                <input type="text" class="form-control form-filter input-sm" name="cust_name" placeholder="Name">
            </td>
            <td>
                <input type="text" class="form-control form-filter input-sm" name="cust_email" placeholder="Email">
            </td>
            <td>
                <input type="text" class="form-control form-filter input-sm" name="cust_mobile" placeholder="Mobile">
            </td>
            <td>
                <button class="btn btn-sm yellow filter-submit margin-bottom"><i class="fa fa-search"></i> Search</button>
            </td>                                       
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>
JavaScript

grid = new Datatable();
grid.init({
    src: $(".ajax-table"),
    onSuccess: function(grid) {
        // execute some code after table records loaded
    },
    onError: function(grid) {
        // execute some code on network or other general error  
    },
    dataTable: {  // here you can define a typical datatable settings from http://datatables.net/usage/options 
        "aLengthMenu": [
            [20, 50, 100, 150, 200],
            [20, 50, 100, 150, 200] 
        ],
        "oLanguage": {  // language settings
            "sProcessing": '<img src="assets/img/loading-spinner-grey.gif"/><span>&nbsp;&nbsp;Loading...</span>',
        },
        "iDisplayLength": 50, // default record count per page
        "bServerSide": true, // server side processing
        "sAjaxSource": "ajax/customers_ajax.php", // ajax source to retrive customer details
        "aaSorting": [[ 1, "asc" ]], // set first column as a default sort by asc
        "aoColumns": [
                      { "sName": "id","bSortable":false,"sWidth":"5%"},
                      { "sName": "cust_name" ,"sWidth":"10%"},
                      { "sName": "cust_email" },
                      { "sName": "cust_mobile","sWidth":"10%"},
                      { "sName": "Action","bSortable":false }
                  ]
    }
});

PHP (Ajax源)

//Identifying column to short on
$columns=explode(",",$_POST['sColumns']); 
$sortCol=$_POST['iSortCol_0'];
$sortOrder=$_POST['sSortDir_0'];
$table="tblcustomer";
$records = array ();
if (isset ( $_REQUEST ["sAction"] ) && $_REQUEST ["sAction"] == "filter") {
    //Counting "TOTAL" number of rows, that can be returned for given "filters"
    $query = "select count(*) total from $table
            where cust_status>-1 ";
    if (!empty( $_REQUEST ['cust_name'] )) {
        $query .= "and cust_name like :cust_name ";
    }
    if (!empty( $_REQUEST ['cust_mobile'] )) {
        $query .= "and cust_mobile like :cust_mobile ";
    }
    if (!empty( $_REQUEST ['cust_email'] )) {
        $query .= "and cust_email like :cust_email ";
    }
    $query = $con->prepare ( $query );
    if (!empty( $_REQUEST ['cust_name'] )) {
        $query->bindValue ( ":cust_name", $_REQUEST ['cust_name'] . "%" );
    }
    if (!empty( $_REQUEST ['cust_mobile'] )) {
        $query->bindValue ( ":cust_mobile", "%".$_REQUEST ['cust_mobile'] . "%" );
    }
    if (!empty( $_REQUEST ['cust_email'] )) {
        $query->bindValue ( ":cust_email", "%".$_REQUEST ['cust_email'] . "%" );
    }
} else {
    //Counting "TOTAL" number of rows in a table --- For non-filter action
    $query = $con->prepare ( "select count(*) total from $table
            where cust_status>-1 " );
}
$query->execute ();
$row = $query->fetch ( PDO::FETCH_ASSOC );
$iTotalRecords = $row ['total'];
$iDisplayLength = intval ( $_REQUEST ['iDisplayLength'] );
$iDisplayLength = $iDisplayLength < 0 ? $iTotalRecords : $iDisplayLength;
$iDisplayStart = intval ( $_REQUEST ['iDisplayStart'] );
$sEcho = intval ( $_REQUEST ['sEcho'] );
$records ["aaData"] = array (); //actual data for Datatable rows.
if (isset ( $_REQUEST ["sAction"] ) && $_REQUEST ["sAction"] == "filter") {
    //Fetching Filtered data
    $query = "SELECT `id`, `cust_name`, `cust_mobile`, `cust_email`
            FROM $table 
            WHERE cust_status>-1 ";
    if (!empty( $_REQUEST ['cust_name'] )) {
        $query .= "and cust_name like :cust_name ";
    }
    if (!empty( $_REQUEST ['cust_mobile'] )) {
        $query .= "and cust_mobile like :cust_mobile ";
    }
    if (!empty( $_REQUEST ['cust_email'] )) {
        $query .= "and cust_email like :cust_email ";
    }
    $query .=" order by {$columns[$sortCol]} {$sortOrder}";
    $query .= " limit $iDisplayStart, $iDisplayLength";
    $query = $con->prepare ( $query );
    if (!empty( $_REQUEST ['cust_name'] )) {
        $query->bindValue ( ":cust_name", $_REQUEST ['cust_name'] . "%" );
    }
    if (!empty( $_REQUEST ['cust_mobile'] )) {
        $query->bindValue ( ":cust_mobile", "%".$_REQUEST ['cust_mobile'] . "%" );
    }
    if (!empty( $_REQUEST ['cust_email'] )) {
        $query->bindValue ( ":cust_email", "%".$_REQUEST ['cust_email'] . "%" );
    }
} else {
    $query = $con->prepare ( "SELECT `id`, `cust_name`, `cust_mobile`, `cust_email` 
            FROM $table`
            WHERE cust_status>-1
            order by {$columns[$sortCol]} {$sortOrder} 
            limit $iDisplayStart, $iDisplayLength" );
}
$query->execute ();
if ($query->rowCount () > 0) {
    while ( $row = $query->fetch ( PDO::FETCH_ASSOC ) ) {
        $edit="<button class='btn btn-warning btn-sm'>Edit</button>";
        $delete="<button class='btn btn-danger btn-sm'>Delete</button>";
        $records ["aaData"] [] = array (
                $row ['id'],
                $row ['cust_name'],
                $row ['cust_email'],
                $row ['cust_mobile'],
                "$edit $delete"
        );
    }
}
$records ["sEcho"] = $sEcho;
$records ["iTotalRecords"] = $iTotalRecords;
$records ["iTotalDisplayRecords"] = $iTotalRecords;
echo json_encode ( $records );

任何帮助/建议都将是感激的。

谢谢!

终于解决了!

使用fnServerParams添加自定义过滤器参数,如下所示:

"fnServerParams": function ( aoData ) {
    //here can be added an external ajax request parameters.
    $('textarea.form-filter, select.form-filter, input.form-filter:not([type="radio"],[type="checkbox"])', table).each(function(){
        aoData.push({"name" : $(this).attr("name"), "value": $(this).val()});
    });
}

它将为每个ajax请求添加自定义参数(分页、排序、过滤等)。每次它都会在过滤器的后端处理中使用那个。

希望对别人有用!