如何在重载数据表时传递参数

BMF*_*BMF 9 javascript ajax jquery datatables jquery-datatables

我有一个数据表,我初始化如下:

mytable = DataTable({
        ajax:{
            url: "/url/getTableData",
            dataSrc: ""

        },
        sortClasses: false,
        paging: false,
        scrollY: 300,
        columns: cols
    });
Run Code Online (Sandbox Code Playgroud)

后来我想做

mytable.ajax.reload();
Run Code Online (Sandbox Code Playgroud)

它工作正常,但现在我想在该请求中发送一些参数.那些参数我只需要重新加载,而不是在表的初始化中.我怎么做?谢谢!

Zen*_*odr 23

选项1 - 使用preXhr.dt事件.

table = $('#example')
    .on('preXhr.dt', function ( e, settings, data ) {
        data.whateveryouwant = $("#someidhere").val()
        data.anotherexample = "kittens"
    } )
// then just setup your datatable as normal
    .DataTable({
        ajax:{
            url: "/url/getTableData",
            type: "GET" // This is the default value, could also be POST
        },
        sortClasses: false,
        paging: false,
        scrollY: 300,
        columns: cols
});
Run Code Online (Sandbox Code Playgroud)

看到这里http://datatables.net/reference/event/

选项2(首选) - 使用ajax.data函数.

table = $('#example').DataTable({
    ajax:{
        url: "/url/getTableData", // Change this URL to where your json data comes from
        type: "GET", // This is the default value, could also be POST, or anything you want.
        data: function(d) {
            d.whateveryouwant = $("#someidhere").val()
            d.anotherexample = "kittens"
        }

    },
    sortClasses: false,
    paging: false,
    scrollY: 300,
    columns: cols
});
Run Code Online (Sandbox Code Playgroud)

两种选择都产生相同的结果 您的服务器不会知道区别.每个都会添加额外的数据table.ajax.reload().额外的数据将是:

whateveryouwant#someidhere元素的价值,和

anotherexample 有价值的 "kittens"

我更喜欢选项2,因为在每个请求中添加额外数据更为明显.第一个选项有点偷偷摸摸,对于其他读我的代码的人来说并不那么明显.