简体   繁体   English

数据表-重新初始化函数中的数据表

[英]Datatables -Reinitializing datatables in a function

I'm still learning how to code js and datatables and I'm working on a crud using ajax. 我仍在学习如何对js和数据表进行编码,并且正在使用ajax编写脚本。 I have this code here: 我在这里有此代码:

        load_data();

         function load_data(is_suppliers)
         {
          var dataTable = $('#product_data').DataTable({
           "processing":true,
           "serverSide":true,
           "order":[],
           "ajax":{
            url:"fetch.php",
            type:"POST",
            data:{is_suppliers:is_suppliers}
           },
           "columnDefs":[
            {
             "targets":[0,5,7,8],
             "orderable":false,
            },
           ],
          });
         }

This function is for column filtering and works with this code here: 此函数用于列过滤,并在此处使用以下代码:

         $(document).on('change', '#supplier_filter', function(){
          var supplier = $(this).val();
          $('#product_data').DataTable().destroy();
          if(supplier != '')
          {
           load_data(supplier);
          }
          else
          {
           load_data();
          }
         });

The problem is that the function initializes datatables: 问题在于该函数初始化了数据表:

          var dataTable = $('#product_data').DataTable({});

and i have already initialized datatables for my crud operations so i cant use this code. 而且我已经为crud操作初始化了数据表,因此无法使用此代码。 How can use this function so it can work with my crud operation? 如何使用此功能,使其可以与我的操作一起使用?

If you define the table's ajax datasource via a function, then you can determine the parameters to send along with your AJAX request at the time the call is made. 如果通过函数定义表的ajax数据源,则可以在调用时确定要与AJAX请求一起发送的参数。 Then, you can reload the datasource whenever you want, and the most current value of the filter will be send along in the payload. 然后,您可以根据需要重新加载数据源,并且过滤器的最新值将在有效负载中发送。

Replace 更换

"ajax":{
  url:"fetch.php",
  type:"POST",
  data:{is_suppliers:is_suppliers}
},

With something like 用类似的东西

ajax: function(data, callback, _settings) {
  $.ajax({
    type: 'POST',
    url: 'fetch.php',
    data: { is_suppliers: $('#supplier_filter').val() }
  }).then(function(res) {
    callback({ data: res });
  });
},

Now, when the table first loads, it'll fetch the filter value from the filter control, and then send it along as part of the AJAX request. 现在,当表第一次加载时,它将从过滤器控件中获取过滤器值,然后将其作为AJAX请求的一部分发送。

Later, you can load the data again with 以后,您可以使用

$('#product_data').DataTable().ajax.reload();

And at that time, it will look again at the filter widget, get the value, and send the new value along with a new AJAX request. 然后,它将再次查看过滤器小部件,获取值,并将新值与新的AJAX请求一起发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM