列表排序不适用于在jQuery中使用数据表的ajax

时间:2018-10-27 04:30:53

标签: javascript jquery ajax laravel datatables

我在laravel中使用jQuery的Datatable通过ajax查看列表,但是当单击排序按钮时,绘制参数增加其值并根据页面对数据进行排序。

我在这里共享一些代码:

我的控制器:

/**
 * listings of organizations table
 * 
 * @param  $request object of Request class
 * @return response json
 */
public function apiListing(Request $request)
{
    $request['page'] = $request['draw'];
    $columns = $request->input('columns');
    $order = $request->input('order');
    $orderField = $columns[$order[0]['column']]['data'];
    $orderDir = $order[0]['dir'];
    $request['s'] = $orderField;
    $request['o'] = $orderDir;
    $request['limit'] = $request->input('length');
    $offset = $request->input('start');
    $request['page'] = $offset < $request['limit'] ? 1 : intval($offset/$request['limit'])+1;
    $utilities = $this->service->paginate($request);
    $totalFiltered = $utilities->total();
    $data = [];

    foreach ($utilities as $key => $utility) {
        $data[] = [
            'utility_id'        => $utility->utility_id,
            'name'              => $utility->name,
            'street_address'    => $utility->street_address,
            'city'              => $utility->city,
            'state_code'        => $utility->state_code,
            'zip'               => $utility->zip,
        ];
    }

    $json_data = array(
                "draw"            => intval($request->input('draw')),
                "recordsTotal"    => intval($totalFiltered),
                "recordsFiltered" => intval($totalFiltered),
                "data"            => $data   
                );

    return response()->json($json_data);
}

我的JavaScript:

function getUtilitiesListingObj()
{
    return new function() {
        this.$tableObj = $('.utilities-listing-table'),
        this.$searchForm = $('#utilitiesSearch'),
        this.$datatableObj = '',
        this.bind = function() {
            var $obj = this;
            $obj.filtering();
            $obj.initiallizeDataTable();
        },
        this.initiallizeDataTable = function() {
            var $obj = this;
            $.extend( $.fn.dataTableExt.oStdClasses, {
                "sFilterInput": "form-control",
                "sLengthSelect": "form-control"
            });

            $obj.$dataTableObj = $obj.$tableObj.DataTable( {
                "pageLength": 100,
                "lengthMenu": [[10, 25, 50, 100, 500], [10, 25, 50, 100, 500]], 
                "order": [[ 1, "asc" ]],
                "stateSave": true,
                "scrollY": "500px",
                "serverSide": true,
                "processing": true,
                "oLanguage": {
                   "sProcessing": "<span>Loading utilities...<span>",
                   "sLengthMenu": "_MENU_"
                },
                "fnDrawCallback": function(o) {
                    $('.dataTables_scrollBody').scrollTop(0);
                },
                "initComplete": function(settings, json) {

                    $('table.utilities-listing-table thead th, table.utilities-listing-table thead td').each(function () {
                       var $td = $(this);
                       $td.attr('title', $td.text());
                    });

                    /* Apply the tooltips */
                    $('table.utilities-listing-table thead th, table.utilities-listing-table thead td').tooltip(
                    {
                       "container": 'body'
                    }); 
                },
                "ajax":{
                        "url": GLOBAL_SETTINGS.UTILITIES_LISTING_URL,
                        "dataType": "json",
                        "type": "get",
                        "data": function(d) {
                            d.name = $('.name-filter').attr('value');
                            d.street_address = $('.address-filter').attr('value');
                            d.city = $('.city-filter').attr('value');
                            d.state = $('.state-filter').attr('value');
                            d.zip = $('.zip-filter').attr('value');
                        }
                },
                "columns": [
                    { "data": "utility_id", "width": "10%" },
                    { "data": "name", "width": "30%" },
                    { "data": "street_address", "width": "20%"},
                    { "data": "city", "width": "10%"},
                    { "data": "state_code", "width": "10%"},
                    { "data": "zip", "width": "10%"},
                ]
            });

        },
        this.filtering = function() {
            var $obj = this;
            $('div.box-body').on('submit', 'form#utilitiesSearch', function() {
                var $form =$(this);
                var $nameObj = $('.name-filter');
                var $addressObj = $('.address-filter');
                var $cityObj = $('.city-filter');
                var $stateObj = $('.state-filter');
                var $zipObj = $('.zip-filter');

                $nameObj.attr('value', $nameObj.val());
                $addressObj.attr('value', $addressObj.val());
                $cityObj.attr('value', $cityObj.val());
                $stateObj.attr('value', $stateObj.val());
                $zipObj.attr('value', $zipObj.val());

                $obj.$dataTableObj.rows().invalidate().draw();
                // $("input[id=hidden_field_name]").val($nameObj.val());
             //    $("input[id=hidden_field_cid]").val($cidObj.val());
                // $("input[id=hidden_field_only_seller_buyer]").val($onlySellerFilerFilter.val());
                return false;
            });
        }
    }
}

当我单击排序按钮时,它不会对数据进行排序,并且draw参数像这样增加其值: enter image description here

1 个答案:

答案 0 :(得分:2)

DataTables 1.10.x的预期行为是随着每个请求绘制值增量。

您还可以在请求中设置第d.page_no = d.start / d.length + 1;页,如下所示:

....
"ajax":{
        "url": GLOBAL_SETTINGS.UTILITIES_LISTING_URL,
        "dataType": "json",
        "type": "get",
        "data": function(d) {
            d.name = $('.name-filter').attr('value');
                d.street_address = $('.address-filter').attr('value');
                d.city = $('.city-filter').attr('value');
                d.state_code = $('.state-filter').attr('value');
                d.zip = $('.zip-filter').attr('value');          
                d.page_no = d.start / d.length + 1;
        }
}
...

还可以像这样在控制器中设置页面编号:

/**
 * listings of organizations table
 * 
 * @param  $request object of Request class
 * @return response json
 */
public function apiListing(Request $request)
{
    $request['page'] = $request['page_no'];
    $columns = $request->input('columns');
    $order = $request->input('order');
    $orderField = $columns[$order[0]['column']]['data'];
    $orderDir = $order[0]['dir'];
    $request['s'] = $orderField;
    $request['o'] = $orderDir;
    $request['limit'] = $request->input('length');
    $offset = $request->input('start');
    $request['page'] = $offset < $request['limit'] ? 1 : intval($offset/$request['limit'])+1;
    $utilities = $this->service->paginate($request);
    $totalFiltered = $utilities->total();
    $data = [];

    foreach ($utilities as $key => $utility) {
        $data[] = [
            'utility_id'        => $utility->utility_id,
            'name'              => $utility->name,
            'street_address'    => $utility->street_address,
            'city'              => $utility->city,
            'state_code'        => $utility->state_code,
            'zip'               => $utility->zip,
        ];
    }

    $json_data = array(
                "Page"            => intval($request->input('page_no')),
                "recordsTotal"    => intval($totalFiltered),
                "recordsFiltered" => intval($totalFiltered),
                "data"            => $data   
                );

    return response()->json($json_data);
}

希望这可以为您提供帮助。 :)