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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24499116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:55:39  来源:igfitidea点击:

how to pass parameters on reload of datatables

javascriptjqueryajaxdatatablesjquery-datatables

提问by BMF

I have a datatable that I initialize like this:

我有一个像这样初始化的数据表:

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

        },
        sortClasses: false,
        paging: false,
        scrollY: 300,
        columns: cols
    });

later I'd like to do

以后我想做

mytable.ajax.reload();

It works fine, but now I'd like to send a few parameters in that request. Those parameters I only need on reload, and not in the initialization of the table. How do I do that? thank you!

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

回答by ZenCodr

Option 1- Use the preXhr.dt event.

选项 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
});

see here http://datatables.net/reference/event/

见这里http://datatables.net/reference/event/

Option 2 (preferred)- Use an ajax.data function.

选项 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
});

Both options produce identical results. Your server will not know the difference. The extra data will be added on every table.ajax.reload(). The extra data will be:

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

whateveryouwantof with value of the #someidhereelement, and

whateveryouwant#someidhere元素的值,和

anotherexamplewith the value "kittens"

anotherexample与价值 "kittens"

I prefer the Option 2, because it's more obvious that extra data is being added on each request. The first option is a little bit sneaky and not as obvious for someone else reading your code I think.

我更喜欢Option 2,因为更明显的是,每个请求都添加了额外的数据。第一个选项有点偷偷摸摸,我认为对于阅读您的代码的其他人来说并不那么明显。