数据表,更改 AJAX 数据(不包含元素)

Datatables, change AJAX data ( not with elements )

我有一个由 AJAX 填充的数据表。一切都很好,但我想要一些快捷方式来从服务器请求数据。问题是我如何更改我正在发送的数据?我知道我可以创建一个元素 <input> 或其他东西,它可以从中获取值,但我希望我可以在单击某些内容后更改数据。

var Table = $('#table').DataTable({
            "ajax": {
                "type" : "POST",
                "url": "url",
                "data": function ( d ) {
                    d.cmd = "offline";
                }
            },
        });

这工作正常并将 cmd 作为 offline 传回服务器。 我如何在调用 ajax.reload 之前更改点击值。

$('#online_btn').on( 'click', function () {
            Table.ajax.reload();
        } );

使用这个

$('#online_btn').on( 'click', function () {
            var d = [];
            d.cmd = "online";
            Table.ajax.data(d);
            Table.ajax.reload();
        } );

返回一个 ajax.data is not a function 错误

在发送对象前使用jqueryajax。

$.ajax({
 url: "http://fiddle.jshell.net/favicon.png",
 beforeSend: function( xhr ) {
   //update your value here
}
})

来源:jquery documentation

beforeSend Type: Function( jqXHR jqXHR, PlainObject settings ) A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.

您可以修改对象并使用 $.extend() 在数据函数中合并

var myData ={};
var Table = $('#table').DataTable({
            "ajax": {
                "type" : "POST",
                "url": "url",
                "data": function ( d ) {
                   return  $.extend(d, myData);
                }
            },
        });

$('#online_btn').on( 'click', function () {            
            myData.cmd = "online";            
            Table.ajax.reload();
});

我在 2021 年这样做:

function customSearch(){
        let t = JSON.parse(window.filter);
        t["custom-field"] =  $('input[name="custom-field"]').val() || "";
        window.filter = JSON.stringify(t);
        return window.filter;
}
const table = $('#table').DataTable({
        ajax:{
           url:"my-wonderful-url.json",
           type:"POST",
           data: function(d) {
            const t = customSearch();
            return  Object.assign(d, {filter:t});
        },
        error:function(e){console.log(e);},            
});
 $('input[name="custom-field"]').on('keyup', function(e){         
    table.ajax.reload(null, false);
});