从服务器获取数据时,数据表显示错误的分页 [英] Datatable showing wrong pagination when get data from server

查看:99
本文介绍了从服务器获取数据时,数据表显示错误的分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网页中,我正在使用datatable显示记录.但是,当我尝试显示数据时,数据显示正确,但分页计数是错误的.

In my webpage, I am using datatable to show the records. But when I try to show the data, data showing correctly but the pagination count is wrong.

我的代码是

oTableSp = $('#specials-table').dataTable({
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": <myUrl>',
    "bJQueryUI": true,
    "sPaginationType": "full_numbers",
    "iDisplayLength":25,
    "lengthMenu": [ 25, 50, 75, 100 ],
    "dom": '<"top"f>rt<"bottom row"<"col-md-3"l><"col-md-3"i><"col-md-6"p>>',
    "columns": [
    {
        data: "SpecialName"
    },
    {
        data: "SpecialFrom"
    },
    {
        data : "SpecialTo"
    },
    {
        data : "SpecialBanner"
    },
    //      {
    //          data : "TermsAndConditions"
    //      },
    {
        data: "Actions",
        "bSortable" : false,
        "aTargets" : [ "no-sort" ]
    }
    ],
    "oLanguage": {
        "sProcessing": "<img src='../assets/admin/img/ajax-loader_dark.gif'>"
    },
    "aaSorting": [],
    "aoColumnDefs": [
    {
        "targets": [0,3],
        "bSortable" : false
    },
    ],
    "dom": '<"top"f>rt<"bottom row"<"col-md-3"l><"col-md-3"i><"col-md-6"p>>',
    'fnServerData': function (sSource, aoData, fnCallback) {
        sSource = sSource;
        aoData.push({
            name: 'csrf_tbd_token', 
            value: tbd_csrf
        });
        $.ajax
        ({
            'dataType': 'json',
            'type': 'POST',
            'url': sSource,
            'data': aoData,
            'success': fnCallback
        });
    },
    'fnCreatedRow': function( nRow, aData, iDataIndex ) {
        $(nRow).attr('data-id',aData['Id']);
    },
    "fnRowCallback" : function(nRow, aData, iDisplayIndex){
        var html = status_html(aData["active"]);
        $("td:eq(4)", nRow).prepend(html);
    },
    fnDrawCallback: function( oSettings ) {
        $(".pagination li").removeClass("ui-button ui-state-default");
        $(".first.disabled, .previous.disabled, .next.disabled, .last.disabled, .fg-button.active").off( "click" );
        $(".first.disabled a, .previous.disabled a, .next.disabled a, .last.disabled a, .fg-button.active a").attr('href','javascript:void(0);');
        $.ajax({
            url: <myUrl>',
            type: 'POST',
            dataType: 'json',
            data:{},
            success: function(data){
                if(data.result == 1){
                    data.message = jQuery.parseJSON(data.message);
                    $.each(data.message, function(index, element) {
                        $('tr[data-id="'+element+'"]').find('.actions').prepend('<a class="approve-sp-all" data-status="1" href="#" title="Approve"><i class="fa fa-fw fa-med fa-thumbs-o-down" style="color:#FF0000"></i></a>');
                    });
                    $('#specials-table tr').each(function(){
                        var elm = $(this);
                        var data_id = elm.attr('data-id');
                        if(jQuery.inArray(data_id, data.message) === -1){
                            $('tr[data-id="'+data_id+'"]').find('.actions').prepend('<a data-status="0" href="#" title="Approved"><i class="fa fa-fw fa-med fa-thumbs-o-up" style="color:#3c763d"></i></a>');
                        }
                    });
                }
            },
            error: function(){

            }
        });

    }
});

当我查看检查元素部分时,它正在显示

When I look in to the inspect element section, it is showing

但是aaData中只有两个记录可以显示.我想念什么吗?请让我知道.

But There is only two records to show as there in the aaData. Am I missing something? Please let me know.

任何帮助都将不胜感激

推荐答案

我们有一个IIS/C#后端,因此我为数据表期望和提供的内容(请求和响应)创建了一些类

We have an IIS/C# back end so I created some classes for what the datatable is expecting and providing (the request and the response)

  #region DataTable (jQuery plugin) related
// the object below are set up to match what 
// the DataTable jQuery plugin expects to see.
// DataTableParameters is set up to match what 
// the plugin sends.
// DataTableData is set up to match what 
// DataTable expects to get.

[Serializable()]
public class DataTableData
{
    private static readonly ILog nepsLog4Net = LogManager.GetLogger("Keport.NEPS.GeneralDataObjects.DataTableData");
    /// <summary>
    /// draw (usually 1) is used by DataTable 
    /// to process async calls in order
    /// in the case of when more than one call is triggered.
    /// </summary>
    public int draw { get; set; }

    /// <summary>
    /// Total records, before filtering (i.e. the total number of records in the database)
    /// </summary>
    public int recordsTotal { get; set; }
    /// <summary>
    /// Total records, after filtering (i.e. the total number of records after filtering has 
    /// been applied - not just the number of records being returned for this page of data).
    /// </summary>
    public int recordsFiltered { get; set; }

    /// <summary>
    /// Data to be displayed in the table
    /// </summary>
    public List<HomePage> data { get; set; }

    /// <summary>
    /// Need to know the total rows and total filter rows
    /// for the DataTable pluging to figure out paging.
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="dtData"></param>
    public static void SetRecordProperties(ref DataSet dt, ref DataTableData dtData)
    {
        try
        {
            if (dt != null && dt.Tables.Count > 1)
            {
                if (dt != null && dt.Tables[1].Rows.Count > 0)
                {
                    dtData.recordsTotal = DSUtil.GetIntFromNullDr(dt.Tables[1].Rows[0], "UnfilteredCount");
                    dtData.recordsFiltered = DSUtil.GetIntFromNullDr(dt.Tables[1].Rows[0], "FilteredCount");
                }
            }
        }
        catch (Exception ex)
        {
            // Error logged but not acted on.
            nepsLog4Net.Error(ex);
            dtData.recordsFiltered = 30;
            dtData.recordsTotal = 30;
        }
    }

}

/// <summary>
/// This object represents what the default search 
/// object, passed back by the client 
/// as part of the DataTable built in AJAX.
/// Each item is documented at their web site.
///  http://datatables.net/manual/server-side
/// </summary>
[Serializable()]
public class DataTableParameters
{
    #region "Properties"
        /// <summary>
        /// Passed directly to the return set.
        /// Used to kept the async calls in order.
        /// </summary>
        public int draw{get; set;}
        /// <summary>
        /// Number of rows to be shown on a page
        /// </summary>
        public int length { get; set; }

        /// <summary>
        /// tab type is used to determine if canned search should be used.
        /// </summary>
        public HomePage.Tabs tabType { get; set; }

        public SearchFor search { get; set; }
        /// <summary>
        /// the row number of used for the starting point 
        /// in creating a page
        /// </summary>
        public int start { get; set; }

        public List<column> columns { get; set; }

        /// <summary>
        /// Sort ordering information to be applied after filtering.
        /// </summary>
        public List<OrderByColumn> order;



    #endregion
        public struct column
        {
            public String data;
            public String name;
            public Boolean orderable;
            public Boolean searchable;
            public SearchFor search;

        }

        public class OrderByColumn
        {
            // column number 
            // db column name can be pulled from the 
            // column object name property
            public int column { get; set; }
            // sorting direction (asc or desc)
            public String dir { get; set; }

        }

        public struct SearchFor
        {
           public Boolean regex;
           public String value;
        }
}
#endregion

这篇关于从服务器获取数据时,数据表显示错误的分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆