在发送

时间:2016-12-30 12:09:38

标签: javascript jquery datatables

我在变量中初始化了DataTable:

var dataTable = $("#selector").DataTable({
    processing: true,
    serverSide: true,
    ajax: $.fn.dataTable.pipeline({
        dataType: "json",
        url: "/path/ajaxurl",
        data: {
            "fruits": "apple",
            "veggies": "banana",
        },
        dataSrc: "data"
    }),
    sPaginationType: "extStyle"
});

现在,在我的脚本中的某处我有这个复选框,当更改时会在上面的ajax上添加新数据然后初始化draw()

$(document).on("change", "#add-some-liquors", function(e) {
    // some validations here

    // My attempt to add this data
    dataTable.data({"drinks" : "coca-cola"});

    // Draw the dataTables
    dataTable.clearPipeline().draw();
});

当我检查后端时,dataTable.data({"drinks" : "coca-cola"});似乎没有在POST上添加饮料,我只得到苹果& banana是两个默认的初始化数据。我错过了什么?

3 个答案:

答案 0 :(得分:2)

根据the API .data方法仅用于检索。尝试在变量中保存数据,更新该对象,然后在.ajax方法中使用它。

var items = {}

ajax: $.fn.dataTable.pipeline({
    dataType: "json",
    url: "/path/ajaxurl",
    data: items,

答案 1 :(得分:1)

将您的数据声明为变量并稍后添加饮品值。

var data = {
            "fruits": "apple",
            "veggies": "banana",
        };

console.log(data);

//On the click event
$('#chk').on('click', function() { 
  if ($(this).is(':checked')) {
     data['drinks'] = 'coca-cola';
  } else {
    //When unchecking the option, set it's value to null
    data['drinks'] = null;

    //Or delete the property.
    //delete data['drinks'];
  }

  console.log(data);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chk" />

答案 2 :(得分:0)

可以将ajax.data对象初始化为一个函数。每次获取数据时都会评估该功能。在此示例中,全局变量selectedDrink的值将与ajax请求一起作为drinks字段发送。

var selectedDrink = "";

var dataTable = $("#selector").DataTable({
    processing: true,
    serverSide: true,
    ajax: $.fn.dataTable.pipeline({
        dataType: "json",
        url: "/path/ajaxurl",
        data: function(d) {
            d.fruits = "apple";
            d.veggies = "banana";
            d.drinks = selectedDrink;
        },
        dataSrc: "data"
    }),
    sPaginationType: "extStyle"
});


$(document).on("change", "#add-some-liquors", function(e) {
    selectedDrink = "coca-cola";

    // Draw the dataTables
    dataTable.clearPipeline().draw();
});