zoukankan      html  css  js  c++  java
  • Jquery DataTable基本使用

    原文:https://www.cnblogs.com/xiashengwang/p/8087181.html

    1,首先需要引用下面两个文件

         <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />

    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>

    2,DataTable支持的数据类型

    https://www.datatables.net/manual/data/

    2.1 数组

    复制代码
    vardata = [
        [
            "Tiger Nixon",
            "System Architect",
            "Edinburgh",
            "5421",
            "2011/04/25",
            "$3,120"
        ],
        [
            "Garrett Winters",
            "Director",
            "Edinburgh",
            "8422",
            "2011/07/25",
            "$5,300"
        ]
    ]
    复制代码

     2.2 对象 

    复制代码
    [
        {
            "name":       "Tiger Nixon",
            "position":   "System Architect",
            "salary":     "$3,120",
            "start_date": "2011/04/25",
            "office":     "Edinburgh",
            "extn":       "5421"
        },
        {
            "name":       "Garrett Winters",
            "position":   "Director",
            "salary":     "$5,300",
            "start_date": "2011/07/25",
            "office":     "Edinburgh",
            "extn":       "8422"
        }
    ]
    复制代码

    2.3 自定义实例(本质和2.2一样) 

    复制代码
    functionEmployee ( name, position, salary, office ) {
        this.name = name;
        this.position = position;
        this.salary = salary;
        this._office = office;
        this.office = function() {
            returnthis._office;
        }
    };   
    

    $('#example').DataTable( {
    data: [
    newEmployee(
    "Tiger Nixon", "System Architect", "$3,120", "Edinburgh"),
    newEmployee(
    "Garrett Winters", "Director", "$5,300", "Edinburgh")
    ],
    columns: [
    { data:
    'name'},
    { data:
    'salary'},
    { data:
    'office'},
    { data:
    'position'}
    ]
    } );

    复制代码

    2.4 datatable的数据来源

    1)DOM

    如果没有指定data,ajax选项,则DataTable会将当前table的html标签上内容转换成对应的数据(Array数据形式)。

    2)Html5

    Data-* 标签上可以指定不同的值,用于排序和查找,td内部标签的值对应当前单元格的数据。

    <td data-search="21st November 2016 21/11/2016" data-order="1479686400">
        21st November 2016
    </td>

      3javascript

      通过data配置,指定数据源。可以通过DataTables API row.add() row().remove()操作行数据。

        4)Ajax 

      通过服务器端分页的方式,取得数据。返回的数据只能是json数组或对象(上面的2.12.2. 

    3,有两种分页方式

    3.1 客户端分页 

    这种方式,代码最简单,整个数据量在10000条以内可以考虑。假设已经有了下面的table: 

    复制代码
    <table id="table1" class="table table-condensed">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Score</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>001</td>
                <td>zhang</td>
                <td>98</td>
            </tr>
            <tr>
                <td>002</td>
                <td>wang</td>
                <td>99</td>
            </tr>
        </tbody>
    </table>
    复制代码

     简单调用一句话(使用默认设置),就可以使table具有排序,查找,分页的基本功能。

    $(function () {
    $("#table1").DataTable({
    });
    });

    3.2 服务器端分页

    这种方式针对大数据量的table(10万条以上),每次只读取当前的一页数据,分页在后台做。代码相对复杂,不过页面响应更快,

    服务器端的分页一般要求我们先定义thead表头,tbody可以不写。

    4,配置参数

    这些配置参数可以通过javascript进行设置,也可以直接用HTML5标签data-* 的方式写在table的标签中。

    所有的配置选项:https://www.datatables.net/reference/option/

    复制代码
     $(function () {
    
        $(</span>"#table1"<span style="color: #000000;">).DataTable({
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 是否允许检索</span>
            "searching": <span style="color: #0000ff;">false</span><span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 是否允许排序</span>
            "ordering": <span style="color: #0000ff;">true</span><span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 初期排序列</span>
            <span style="color: #008000;">//</span><span style="color: #008000;">"order": [[0,'asc'],[1,'desc']],</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> 是否显示情报 就是"当前显示1/100记录"这个信息</span>
            "info": <span style="color: #0000ff;">false</span><span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 是否允许翻页,设成false,翻页按钮不显示</span>
            "paging": <span style="color: #0000ff;">false</span><span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 水平滚动条</span>
            "scrollX": <span style="color: #0000ff;">false</span><span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 垂直滚动条</span>
            "scrollY": <span style="color: #0000ff;">false</span><span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 件数选择功能 默认true</span>
            "lengthChange": <span style="color: #0000ff;">false</span><span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 件数选择下拉框内容</span>
            "lengthMenu": [10, 25, 50, 75, 100<span style="color: #000000;">],
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 每页的初期件数 用户可以操作lengthMenu上的值覆盖</span>
            "pageLength": 50<span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;">翻页按钮样式</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> numbers:数字</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> simple:前一页,后一页</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> simple_numbers:前一页,后一页,数字</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> full:第一页,前一页,后一页,最后页</span>
            <span style="color: #008000;">//</span><span style="color: #008000;">full_numbers:第一页,前一页,后一页,最后页,数字</span>
            <span style="color: #008000;">//</span><span style="color: #008000;">first_last_numbers:第一页,最后页,数字</span>
            "pagingType": "full_numbers"<span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 行样式应用 指定多个的话,第一行tr的class为strip1,第二行为strip2,第三行为strip3.</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> 第四行以后又开始从strip1循环。。。 如果想指定成斑马条状,这里的class必须指定为2个。</span>
            "stripeClasses": ['strip1', 'strip2', 'strip3'<span style="color: #000000;">],
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 自动列宽</span>
            "autoWidth": <span style="color: #0000ff;">true</span><span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 是否表示 "processing" 加载中的信息,这个信息可以修改</span>
            "processing": <span style="color: #0000ff;">true</span><span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 每次创建是否销毁以前的DataTable,默认false</span>
            "destroy": <span style="color: #0000ff;">false</span><span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 控制表格各种信息的表示位置(比较复杂) 默认:lfrtip</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> 具体参考:https://datatables.net/reference/option/dom</span>
            "dom": 'lrtip'<span style="color: #000000;">,
            </span>"language"<span style="color: #000000;">: {
                </span>"processing": "DataTables is currently busy"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 当前页显示多少条</span>
                "lengthMenu": "Display _MENU_ records"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> _START_(当前页的第一条的序号) ,_END_(当前页的最后一条的序号),_TOTAL_(筛选后的总件数),</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> _MAX_(总件数),_PAGE_(当前页号),_PAGES_(总页数)</span>
                "info": "Showing page _PAGE_ of _PAGES_"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 没有数据的显示(可选),如果没指定,会用zeroRecords的内容</span>
                "emptyTable": "No data available in table"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 筛选后,没有数据的表示信息,注意emptyTable优先级更高</span>
                "zeroRecords": "No records to display"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 千分位的符号,只对显示有效,默认就是","  一般不要改写</span>
                <span style="color: #008000;">//</span><span style="color: #008000;">"thousands": "'",</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> 小数点位的符号,对输入解析有影响,默认就是"." 一般不要改写</span>
                <span style="color: #008000;">//</span><span style="color: #008000;">"decimal": "-",</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> 翻页按钮文字控制</span>
                "paginate"<span style="color: #000000;">: {
                    </span>"first": "First page"<span style="color: #000000;">,
                    </span>"last": "Last page"<span style="color: #000000;">,
                    </span>"next": "Next page"<span style="color: #000000;">,
                    </span>"previous": "Previous page"<span style="color: #000000;">
                },
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> Client-Side用,Server-Side不用这个属性</span>
                "loadingRecords": "Please wait - loading..."<span style="color: #000000;">
            },
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 默认是false</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> 如果设为true,将只渲染当前也的html,速度会很快,但是通过API就访问不到所有页的数据,有利有弊</span>
            <span style="color: #008000;">//</span><span style="color: #008000;">"deferRender": false,</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> 服务器端处理方式</span>
            "serverSide": <span style="color: #0000ff;">true</span><span style="color: #000000;">,
    
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> ajax选项 可以直接简单指定成请求的文件</span>
            <span style="color: #008000;">//</span><span style="color: #008000;">"ajax": "data.json",</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> 也可以用对象来配置,更加灵活</span>
            "ajax"<span style="color: #000000;">: {
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> url可以直接指定远程的json文件,或是MVC的请求地址 /Controller/Action</span>
                url: "data.json"<span style="color: #000000;">,
                type: </span>'POST'<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 传给服务器的数据,可以添加我们自己的查询参数</span>
                data: <span style="color: #0000ff;">function</span><span style="color: #000000;"> (param) {
                    param.opportunityNO </span>= $('#txtSearch'<span style="color: #000000;">).val();
                    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> param;
                },
                </span><span style="color: #008000;">//</span><span style="color: #008000;">用于处理服务器端返回的数据。 dataSrc是DataTable特有的</span>
                dataSrc: <span style="color: #0000ff;">function</span><span style="color: #000000;"> (myJson) {
                    </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (myJson.timeout) {
                        </span><span style="color: #0000ff;">return</span> ""<span style="color: #000000;">;
                    }
                    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> myJson;
                }
            },
            </span><span style="color: #008000;">//</span><span style="color: #008000;">指定用于行ID的属性名 默认是:DT_RowId</span>
            "rowId": 'staffId'<span style="color: #000000;">,
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 列定义</span>
            "columns"<span style="color: #000000;">: [            
            {
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> data 可以是属性名,或嵌套属性(WORKTM1.ID),数组ArrOne[,] 用中括号中的字符连接数组后返回。</span>
                "data": "WORKTM1"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 这里的class会应用到td上面</span>
                "className": "dt-body-right"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 列宽</span>
                "width": 40<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 很灵活,描绘每个单元格</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> data:当前cell的data,这个data和type有关</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> type:filter,display,type,sort</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> row:当前行数据</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> https://datatables.net/reference/option/columns.render</span>
                "render": <span style="color: #0000ff;">function</span><span style="color: #000000;"> (data, type, row, meta) {
                    </span><span style="color: #0000ff;">return</span> type === 'display' &amp;&amp; data.length &gt; 40 ?
                    '&lt;span title="' + data + '"&gt;' + data.substr(0, 38) + '...&lt;/span&gt;'<span style="color: #000000;"> : data;
    
                },
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 是否可排序 默认值:true</span>
                "orderable": <span style="color: #0000ff;">true</span><span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 指定当前列排序操作的时候,用哪一列(几列)的数据进行真正的排序(通常是隐藏的)</span>
                "orderData": [0, 1<span style="color: #000000;">],
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 这个属性 和type属性相似,指定排序时候这一列该怎么转换数据,</span>
                <span style="color: #008000;">//</span><span style="color: #008000;">需要用到其他的插件 详细: https://datatables.net/plug-ins/sorting/</span>
                "orderDataType": "dom-text"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 是否显示当前列 默认值:true</span>
                "visible": <span style="color: #0000ff;">false</span><span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 是否允许搜索此列 默认值:true</span>
                "searchable": <span style="color: #0000ff;">false</span><span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;">这个属性仅Client-Side有效, Server-Side在服务器端排序 </span>
                <span style="color: #008000;">//</span><span style="color: #008000;">主要用于排序和筛选,指定当前列作为什么类型进行解析</span>
                <span style="color: #008000;">//</span><span style="color: #008000;">内置值:date,num,num-fmt,html-num,html-num-fmt,html,string</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> 还可以用其他插件提供的类型 :详细: https://datatables.net/plug-ins/sorting/</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> 有html开头的,都会讲html标签先移除后进行数据处理</span>
                "type": "html"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 列头文字,如果没有指定thead,则会生成。如何指定了thead,则会覆盖当前列头文字</span>
                "title": "My column title"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> defaultContent:默认值,属性值为null或undefined就会用这个值</span>
                "defaultContent": "&lt;i&gt;Not set&lt;/i&gt;"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 单元格类型:"th","td"</span>
                "cellType" : "td"<span style="color: #000000;">,
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 单元格创建完后的回调,可以作为render的补充</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> cell:TD的dom</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> cellData:原始的单元格数据,如何render中进行了格式化,用$(cell).html()来取格式化后的数据</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> rowData:行数据</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> row:行号</span>
                <span style="color: #008000;">//</span><span style="color: #008000;"> col:列号</span>
                "createdCell": <span style="color: #0000ff;">function</span><span style="color: #000000;"> (cell, cellData, rowData, row, col) {
                    </span><span style="color: #0000ff;">if</span> ( cellData &lt; 1<span style="color: #000000;"> ) {
                        $(td).css(</span>'color', 'red'<span style="color: #000000;">)
                    }
                }
            },
            { </span>"data": "WORKTM2", "className": "dt-body-right", "width": 40<span style="color: #000000;"> },
            { </span>"data": "WORKTM3", "className": "dt-body-right", "width": 40<span style="color: #000000;"> },
            { </span>"data": "WORKTM4", "className": "dt-body-right", "width": 40<span style="color: #000000;"> },
            { </span>"data": "RESTDAY1", "className": "dt-body-right", "width": 40<span style="color: #000000;"> },
            { </span>"data": "RESTDAY2", "className": "dt-body-right", "width": 40<span style="color: #000000;"> },
            { </span>"data": "RESTDAY3", "className": "dt-body-right", "width": 40<span style="color: #000000;"> },
            { </span>"data": "RESTDAY4", "className": "dt-body-right", "width": 40<span style="color: #000000;"> },
            { </span>"data": "RESTDAY5", "className": "dt-body-right", "width": 40<span style="color: #000000;"> }
            ],
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 和上面的columns类似,columns可以定义的属性,都可以在这里定义,</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> 另外增加targets属性用于指定列范围(可以多列)</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> 优先级:上面的columns高于columnDefs</span>
    

    columnDefs: [
    {
    targets: [
    0, 2],
    render:
    function (data, type, row, meta) {
    if (type === 'display') {
    var ctemp = $(".dayinfo").children().eq(meta.col).attr("class");
    var cname = ctemp ? ctemp : "";
    var readonly = $(".dayinfo").children().eq(meta.col).attr("data-fixed") == "fixed" ? "readonly" : "";
    return '<input type="input" class="form-control dt-body-center ' + cname + '" ' + readonly + ' value="' + data + '">';
    }
    return data;
    },
    }],
    // 每一行创建完调用的函数
    "createdRow": function (row, data, dataIndex) {
    // row : tr dom
    // data: row data
    // dataIndex:row data's index
    if (data[4] == "A") {
    $(row).addClass(
    'important');
    }
    },
    // 每一行被创建,但还没有被加载到document中,这个函数优先于createdRow
    // 个人觉得用createdRow更好
    "rowCallback": function (row, data, index) {
    // row : tr dom
    // data: row data
    // index:row data's index
    if ( data[4] == "A" ) {
    $(
    'td:eq(4)', row).html( '<b>A</b>' );
    }
    },
    //thead被描画后调用
    "headerCallback": function (thead, data, start, end, display) {
    //thead:dom, data:原始的datatable数据,display:当前显示排序好的datatable数据(有可能经过排序)
    // start end :当前dispaly数据的开始结束序号
    $(thead).find('th').eq(0).html( 'Displaying '+(end-start)+' records' );
    },
    // tfoot被描画后调用,通常可用于计算合计值
    "footerCallback": function (tfoot, data, start, end, display) {
    //tfoot:dom, data:原始的datatable数据,display:当前显示排序好的datatable数据(有可能经过排序)
    // start end :当前dispaly数据的开始结束序号
    var api = this.api();
    $( api.column(
    5 ).footer() ).html(
    api.column(
    5 ).data().reduce( function ( a, b ) {
    return a + b;
    },
    0 )
    );
    },
    // 初始化,描画都已经完成,常用于ajax
    "initComplete": function( settings, json ) {
    $(
    'div.loading').remove();
    },
    // 每次DataTable描画后都要调用,调用这个函数时,table可能没有描画完成,
    // 所以不要在里面操作table的dom,要操作dom应放在initComplete
    "drawCallback": function( settings ) {
    var api = this.api();

                </span><span style="color: #008000;">//</span><span style="color: #008000;"> Output the data for the visible rows to the browser's console</span>
                console.log( api.rows( {page:'current'<span style="color: #000000;">} ).data() );
            },
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 这个函数可以改写数字的格式化方式</span>
            <span style="color: #008000;">//</span><span style="color: #008000;"> 默认DataTable用 language.thousands来解析数字,“,”</span>
            "formatNumber": <span style="color: #0000ff;">function</span><span style="color: #000000;"> ( toFormat ) {
                </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> toFormat.toString().replace(
                  </span>/B(?=(d{3})+(?!d))/g, "'"<span style="color: #000000;">
                );
            }
        });
    });</span></pre>
    
    复制代码

    5,服务器端的参数

    复制代码
        // 发送到服务器端的数据
        // draw:计数器,返回数据的时候用这个值设定
        // start:开始记录(0 besed index)
        // length:每页条数
        // search[value]:检索文字
        // order[i][column]:int 排序列的序号 例如:2,代表第3列排序 i代表有几个排序,一个的话服务器端这样写“order[0][column]”
        // order[i][dir]:排序的方式"desc","asc"
        // 下面comuns中的i取值从0~columns.length,所有的columns信息都发送到了服务器
        // columns[i][data]:columns上定义的data属性值
        // columns[i][name]:columns上定义的name属性值
        // columns[i][searchable]:列能不能检索
        // columns[i][orderable]:列能不能排序
        // columns[i][search][value]:列的检索值 string
    
    <span style="color: #008000;">//</span><span style="color: #008000;"> 服务器返回的数据</span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> draw:和Request的draw设定成一样的值</span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> recordsTotal:所有的总件数</span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> recordsFiltered:筛选后的总件数</span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> data:返回的数据</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">   每一行数据上面,可以包含这几个可选项</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">   DT_RowId:加在行上的ID值</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">   DT_RowClass:加在行上的Class</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">   DT_RowData:加在行上的额外数据(object)</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">   DT_RowAttr:加在行上的属性(object)</span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> error:如果有错误,就设定这个值,没有错误,不要包含这个值</span></pre>
    
    复制代码

    例子:

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Configuration;
    using AppBlock;
    using System.Data.SqlClient;
    using Newtonsoft.Json;
    

    namespace alfest.Ajax
    {
    public partial class Category : System.Web.UI.Page
    {
    string mode, option, user, limit, start, searchKey, orderByColumn, orderByDir, estMstSrno, pnlsrno, draw, jsonString;
    CommonClass cmnCls
    = new CommonClass();
    protected void Page_Load(object sender, EventArgs e)
    {
    mode
    = Request.QueryString["mode"] == null ? "" : Request.QueryString["mode"].ToString();
    option
    = Request.QueryString["option"] == null ? "" : Request.QueryString["option"].ToString();
    limit
    = Request.QueryString["length"] == null ? "" : Request.QueryString["length"].ToString();
    start
    = Request.QueryString["start"] == null ? "" : Request.QueryString["start"].ToString();
    user
    = Request.QueryString["user"] == null ? "" : Request.QueryString["user"].ToString();
    searchKey
    = Request.QueryString["search[value]"] == null ? "" : Request.QueryString["search[value]"].ToString();
    orderByColumn
    = Request.QueryString["order[0][column]"] == null ? "" : Request.QueryString["order[0][column]"].ToString();
    orderByDir
    = Request.QueryString["order[0][dir]"] == null ? "" : Request.QueryString["order[0][dir]"].ToString();
    estMstSrno
    = Request.QueryString["estMstSrno"] == null ? "" : Request.QueryString["estMstSrno"].ToString();
    pnlsrno
    = Request.QueryString["pnlsrno"] == null ? "" : Request.QueryString["pnlsrno"].ToString();
    draw
    = Request.QueryString["draw"] == null ? "" : Request.QueryString["draw"].ToString();

      </span><span style="color: #0000ff;">if</span> (option == <span style="color: #800000;">"</span><span style="color: #800000;">GetAllAdminCategory</span><span style="color: #800000;">"</span><span style="color: #000000;">)
      {
    
       </span><span style="color: #008000;">//</span><span style="color: #008000;"> Cls_Category CatgObj = new Cls_Category();
       </span><span style="color: #008000;">//</span><span style="color: #008000;"> CatgObj.orderColumn = Convert.ToInt32(orderByColumn);
       </span><span style="color: #008000;">//</span><span style="color: #008000;"> CatgObj.limit = Convert.ToInt32(limit);
       </span><span style="color: #008000;">//</span><span style="color: #008000;"> CatgObj.orderDir = orderByDir;
       </span><span style="color: #008000;">//</span><span style="color: #008000;"> CatgObj.start = Convert.ToInt32(start);
       </span><span style="color: #008000;">//</span><span style="color: #008000;"> CatgObj.searchKey = searchKey;
       </span><span style="color: #008000;">//</span><span style="color: #008000;"> CatgObj.option = "GetAllAdminCategory";
    
      </span><span style="color: #008000;">//</span><span style="color: #008000;"> or user your own method to get data (just fill the dataset)
    
      </span><span style="color: #008000;">//</span><span style="color: #008000;">  DataSet ds = cmnCls.PRC_category(CatgObj);</span>
    
        <span style="color: #0000ff;">dynamic</span> newtonresult = <span style="color: #0000ff;">new</span><span style="color: #000000;">
          {
            status </span>= <span style="color: #800000;">"</span><span style="color: #800000;">success</span><span style="color: #800000;">"</span><span style="color: #000000;">,
            draw </span>= Convert.ToInt32(draw == <span style="color: #800000;">""</span> ? <span style="color: #800000;">"</span><span style="color: #800000;">0</span><span style="color: #800000;">"</span><span style="color: #000000;"> : draw),
            recordsTotal </span>= ds.Tables[<span style="color: #800080;">1</span>].Rows[<span style="color: #800080;">0</span>][<span style="color: #800080;">0</span><span style="color: #000000;">],
            recordsFiltered </span>= ds.Tables[<span style="color: #800080;">1</span>].Rows[<span style="color: #800080;">0</span>][<span style="color: #800080;">0</span><span style="color: #000000;">],
            data </span>= ds.Tables[<span style="color: #800080;">0</span><span style="color: #000000;">]
          };
        jsonString </span>=<span style="color: #000000;"> JsonConvert.SerializeObject(newtonresult);
    
        Response.Clear();
        Response.ContentType </span>= <span style="color: #800000;">"</span><span style="color: #800000;">application/json</span><span style="color: #800000;">"</span><span style="color: #000000;">;
        Response.Write(jsonString);
    
      }
    }
    

    }
    }

    复制代码

    6,DataTable常用事件 

    复制代码
        //常用事件
        // init:初始化和数据都加载完成,和 initComplete配置等价
        $('#example')
        .on('init.dt', function () {
            console.log('Table initialisation complete: ' + new Date().getTime());
        })
        .dataTable();
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> error:处理数据出错 errMode必须为“none”,才会触发error事件</span>
    $.fn.dataTable.ext.errMode = 'none'; <span style="color: #008000;">//</span><span style="color: #008000;"> alert,throw,none, a function</span>
    $('#example'<span style="color: #000000;">)
        .on(</span>'error.dt', <span style="color: #0000ff;">function</span><span style="color: #000000;"> (e, settings, techNote, message) {
            console.log(</span>'An error has been reported by DataTables: '<span style="color: #000000;">, message);
        })
        .DataTable();
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> xhr:ajax加载数据完成后调用,这时数据并没有被描画,等价于 ajax.dataSrc</span>
    $('#example'<span style="color: #000000;">)
    .on(</span>'xhr.dt', <span style="color: #0000ff;">function</span><span style="color: #000000;"> (e, settings, json, xhr) {
        </span><span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">var</span> i = 0, ien = json.aaData.length ; i &lt; ien ; i++<span style="color: #000000;">) {
            json.aaData[i].sum </span>= json.aaData[i].one +<span style="color: #000000;"> json.aaData[i].two;
        }
        </span><span style="color: #008000;">//</span><span style="color: #008000;"> Note no return - manipulate the data directly in the JSON object.</span>
    

    })
    .dataTable({
    ajax:
    "data.json"
    });

    复制代码

    7,Datatable常用Api

    复制代码
        //全部参考 https://datatables.net/reference/api/
        // 1,获取API的方式
        // 注意 $(selector).dataTable()得到的是table的jquery对象
        // 而api对象只能通过:api.$(select) 返回查找到的jquery对象。
        $(selector).DataTable();
        $(selector).dataTable().api();
        new $.fn.dataTable.Api(selector);
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 2,得到一个api对象</span>
    <span style="color: #0000ff;">var</span> table = $('#example'<span style="color: #000000;">).DataTable();
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;">3,描画 draw( [paging] ) 取值:true 全部重画,false 全部重画(保持当前的页面),</span>
    

    // "page" 不重取数据,只描画当前页
    $('#myFilter').on('keyup', function () {
    table.search(
    this.value).draw();
    });

    </span><span style="color: #008000;">//</span><span style="color: #008000;"> Sort by column 1 and then re-draw</span>
    table.order([[1, 'asc']]).draw(<span style="color: #0000ff;">false</span><span style="color: #000000;">);
    table.page(</span>'next').draw('page'<span style="color: #000000;">);
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> data() 获取全表数据</span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> Increment a counter for each row</span>
    table.data().each(<span style="color: #0000ff;">function</span><span style="color: #000000;"> (d) {
        d.counter</span>++<span style="color: #000000;">;
    });
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 4,column().data() 获取列数据</span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> cloumn的第一个参数 可以是序号,或jquery支持的选择器</span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> cloumn的第二个参数 是一个 selector-modifier  对象,取值如下</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">{</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">    // DataTables core</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">    order:  'current',  // 'current', 'applied', 'index',  'original'</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">    page:   'all',      // 'all',     'current'</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">    search: 'none',     // 'none',    'applied', 'removed'</span>
    
    <span style="color: #008000;">//</span><span style="color: #008000;">    // Extension - KeyTable (v2.1+) - cells only</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">    focused: undefined, // true, false, undefined</span>
    
    <span style="color: #008000;">//</span><span style="color: #008000;">    // Extension - Select (v1.0+)</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">    selected: undefined // true, false, undefined</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">}</span>
    table.column(3, { order: 'current'<span style="color: #000000;"> }).data();
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;">5,row().data() 获取行数据</span>
    $('#example tbody').on('click', 'tr', <span style="color: #0000ff;">function</span><span style="color: #000000;"> () {
        console.log(table.row(</span><span style="color: #0000ff;">this</span><span style="color: #000000;">).data());
    });
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 6,row().node() 获取行dom对象</span>
    $(table.row('#row-4').node()).addClass('ready'<span style="color: #000000;">);
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 7,row().remove(); 删除当前行</span>
    table.row('#row-4'<span style="color: #000000;">).remove();
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 8, row.add() 加一行数据</span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> rows.add() 加多行数据</span>
    table.row.add({id:"1",name:"li"<span style="color: #000000;">});
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 9, table().body() 获取tbody dom 对象 </span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> table().header() 获取theader dom 对象 </span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> table().footer() 获取tfooter dom 对象 </span>
    <span style="color: #008000;">//</span><span style="color: #008000;"> table().node() 获取table dom 对象 </span>
    $(table.table().footer()).addClass('highlight'<span style="color: #000000;">);
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 10,destroy() 销毁table true:连同html一起销毁</span>
    table.destroy(<span style="color: #0000ff;">false</span><span style="color: #000000;">)
    
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 11,on 绑定table的事件</span>
    table.on('xhr', <span style="color: #0000ff;">function</span><span style="color: #000000;"> (e, settings, json) {
        console.log(</span>'Ajax event occurred. Returned data: '<span style="color: #000000;">, json);
    });
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> 12,page.len(10) 设置一页显示的条数</span>
    $('#_10').on('click', <span style="color: #0000ff;">function</span><span style="color: #000000;"> () {
        table.page.len(</span>10<span style="color: #000000;">).draw();
    });</span></pre>
    
    复制代码

      8,其他

    8.1   重新加载数据

    第二个参数为false的话,会保持当前的选中页。

    复制代码
    vartable = $('#example').DataTable();
    

    table.ajax.reload( function( json ) {

    $(</span>'#myInput'<span style="color: #000000;">).val( json.lastInput );
    

    } , true);

    复制代码

    8.2 改变url,再加载 

    table.ajax.url( 'newData.json').load();

    8.3 获取服务器返回的json数据

    复制代码
    vartable = $('#example').DataTable();
    

    table.on( 'xhr', function() {

    varjson </span>=<span style="color: #000000;"> table.ajax.json();
    
    alert( json.data.length </span>+' row(s) were loaded'<span style="color: #000000;">);
    

    } );

    复制代码
  • 相关阅读:
    roundabout插件使用(3d旋转轮播图)兼容IE8
    css实现定高的元素在不定高的容器中水平垂直居中(兼容IE8及以上)
    jq点击小图 弹出大图(更新版)
    pc端页面在移动端显示问题
    swiper横向轮播--3d
    swiper横向轮播(兼容IE8)
    windows 7安装apache
    从SDP中至少要看到那些东西?
    FS拓展设置
    Freeswitch 入门
  • 原文地址:https://www.cnblogs.com/showcase/p/11547113.html
Copyright © 2011-2022 走看看