【问题标题】:Access DataTable data returned from server访问服务器返回的 DataTable 数据
【发布时间】:2020-08-08 09:16:04
【问题描述】:

我正在实现一个复选框来选择所有行,但只选择当前页面中的行。

所以我试图访问返回的数据对象,以便我可以实现我的逻辑来检查所有复选框。

这是我的代码:

$.fn.dataTable.pipeline = function ( opts ) {
// Configuration options

var conf = $.extend( {
    pages: 5,     // number of pages to cache
    url: opts.url,      // script url
    data: opts.data,   // function or object with parameters to send to the server
                  // matching how `ajax.data` works in DataTables
    method: 'post' // Ajax HTTP method
}, opts );
// Private variables for storing the cache
var cacheLower = -1;
var cacheUpper = null;
var cacheLastRequest = null;
var cacheLastJson = null;

return function ( request, drawCallback, settings ) {
    var ajax          = false;
    var requestStart  = request.start;
    var drawStart     = request.start;
    var requestLength = request.length;
    var requestEnd    = requestStart + requestLength;
    if ( settings.clearCache ) {
        // API requested that the cache be cleared
        ajax = true;
        settings.clearCache = false;
      
    }
    else if ( cacheLower < 0 || requestStart < cacheLower || requestEnd > cacheUpper ) {
        // outside cached data - need to make a request
        ajax = true;
    }
    else if ( JSON.stringify( request.order )   !== JSON.stringify( cacheLastRequest.order ) ||
              JSON.stringify( request.columns ) !== JSON.stringify( cacheLastRequest.columns ) ||
              JSON.stringify( request.search )  !== JSON.stringify( cacheLastRequest.search )
    ) {
        // properties changed (ordering, columns, searching)

        ajax = true;
    }
     
    // Store the request for checking next time around
    cacheLastRequest = $.extend( true, {}, request );

    if ( ajax ) {
        // Need data from the server
        // console.log(requestLength)
        if ( requestStart < cacheLower ) {
            requestStart = requestStart - (requestLength*(conf.pages-1));

            if ( requestStart < 0 ) {
                requestStart = 0;
            }
        }
         
        cacheLower = requestStart;
        cacheUpper = requestStart + (requestLength * conf.pages);

        request.start = requestStart;
        request.length = requestLength*conf.pages;

        // Provide the same `data` options as DataTables.
        if ( typeof conf.data === 'function' ) {
            // As a function it is executed with the data object as an arg
            // for manipulation. If an object is returned, it is used as the
            // data object to submit
            var d = conf.data( request );
            if ( d ) {
                $.extend( request, d );
            }
        }
        else if ( $.isPlainObject( conf.data ) ) {
            // As an object, the data given extends the default
            // console.log('=====================================')
            // console.log('yes its a data')
            $.extend( request, conf.data );
        }

        return $.ajax( {
            "type":     conf.method,
            "url":      conf.url,
            "data":     request,
            "dataType": "json",
            "cache":    false,
            "success":  function ( json ) {
              console.log(json)
                cacheLastJson = $.extend(true, {}, json);

                if ( cacheLower != drawStart ) {
                    json.aaData.splice( 0, drawStart-cacheLower );
                }
                if ( requestLength >= -1 ) {
                    json.aaData.splice( requestLength, json.aaData.length );
                }

                drawCallback( json );
            }
        } );
    }
    else {
        json = $.extend( true, {}, cacheLastJson );
        json.draw = request.draw; // Update the echo for each response
        json.aaData.splice( 0, requestStart-cacheLower );
        json.aaData.splice( requestLength, json.aaData.length );
        drawCallback(json);
    }
}
};

// Register an API method that will empty the pipelined data, forcing an Ajax
// fetch on the next draw (i.e. `table.clearPipeline().draw()`)
$.fn.dataTable.Api.register( 'clearPipeline()', function () {
return this.iterator( 'table', function ( settings ) {
    settings.clearCache = true;
} );
} );

function triggerTable(data){
 var table = $('#example').DataTable({
//   fixedHeader: true,
  "lengthMenu": [[10, 100, 500], [10, 100, 500]],
  'processing': true,
  'serverSide': true,
  'serverMethod': 'post',
  "order": [[ 5, "desc" ]],
  "ajax": $.fn.dataTable.pipeline( {
        url: '<?php echo base_url()?>Masters_cntrl/orgPartnerEmpList_AJAXPagination',
        data: data,
        pages: data.fetchCount, // number of pages to cache
    } ),
  'columns': [
    { data: 'checkbox' },
     { data: 'status' },
     { data: 'member_fullname'},
     { data: 'member_mobile_no' },
     { data: 'organization_name' },
  ]
});
return table;
}
var data = {
  'org_id' : '<?php echo $org_id ?>',
  'query'   : '<?php echo $Query ?>',
  'fetchCount' : 5,
};
var table =  triggerTable(data);

而且,下面是我试图访问所有记录的代码

   $('#selectAll').on('click', function(){
      $("#example").find("tr").each(function (e) {
        console.log(e)
      });
   });

但它只显示当前页面的十条记录。

【问题讨论】:

  • 你有没有偶然尝试过this
  • 是的,它来自我正在开发的应用程序的代码。这是一个工作代码。我唯一需要的是访问返回的数据。
  • 我需要遍历所有表格行,但是我无法循环超过前十条记录

标签: jquery datatables pipeline


【解决方案1】:

您可以使用 DataTables column().nodes() 函数访问一列中的所有 HTML 单元格(跨所有结果页面),然后您可以从那里处理复选框。

假设你有一个这样的按钮:

<button type="button" onclick="selectAllRows()">Select All</button>

还有一些表格数据(用于测试)是这样的:

    <table id="example" class="display dataTable cell-border" style="width:100%">
        <thead>
            <tr>
                <th></th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011/07/25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009/01/12</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2012/03/29</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>33</td>
                <td>2008/11/28</td>
                <td>$162,700</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Brielle Williamson</td>
                <td>Integration Specialist</td>
                <td>New York</td>
                <td>61</td>
                <td>2012/12/02</td>
                <td>$372,000</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Herrod Chandler</td>
                <td>Sales Assistant</td>
                <td>San Francisco</td>
                <td>59</td>
                <td>2012/08/06</td>
                <td>$137,500</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Rhona Davidson</td>
                <td>Integration Specialist</td>
                <td>Tokyo</td>
                <td>55</td>
                <td>2010/10/14</td>
                <td>$327,900</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Colleen Hurst</td>
                <td>Javascript Developer</td>
                <td>San Francisco</td>
                <td>39</td>
                <td>2009/09/15</td>
                <td>$205,500</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Sonya Frost</td>
                <td>Software Engineer</td>
                <td>Edinburgh</td>
                <td>23</td>
                <td>2008/12/13</td>
                <td>$103,600</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Jena Gaines</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>30</td>
                <td>2008/12/19</td>
                <td>$90,560</td>
            </tr>
            <tr>
                <td><input type = "checkbox"></td>
                <td>Quinn Flynn</td>
                <td>Support Lead</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2013/03/03</td>
                <td>$342,000</td>
            </tr>
        </tbody>
    </table>

然后您可以使用以下脚本循环遍历表中的每一行(跨所有页面):

<script type="text/javascript">

$(document).ready(function() {
  $('#example').DataTable();
} );

function selectAllRows() {
  var table = $('#example').dataTable().api();
  table.column(0).nodes().each( function ( cell, index ) {
    $('input', cell).prop('checked', true);
  } );
}

</script>

这使用 DataTables api() 调用来获取对 DataTable 的引用。

然后它遍历第一列(列索引 0)中的每个节点。这为我们提供了第一列中的&lt;td&gt; 单元格。

最后,函数在选定的单元格中设置复选框。

您可以在文档here 中阅读有关column().nodes() 的更多信息。

当我导航到记录的第二页时,我可以看到它们已经被选中:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    相关资源
    最近更新 更多