导出ajax / serverside datatable的最佳方式 [英] Best way to export ajax/serverside datatable

查看:139
本文介绍了导出ajax / serverside datatable的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的应用程序,我有一个使用ajax检索记录的datatable。数据表允许用户进行排序,搜索,并添加了一个额外的自定义字段,允许用户根据类别进行过滤。



现在,当我使用数据表提供的HTML5方法导出到CSV / Excel时,我只得到导出中显示在浏览器中的记录。所以,我唯一的选择是做服务器端导出。我有一个工作的出口功能,但我正在努力找到正确的方法来将我的过滤器传递给此导出功能。



我不知道最好的方式是在我的模型中获取我的导出方法的参数。我考虑包括jQuery来添加参数到我的link_to,但我不知道如何做到这一点,如果这被认为是良好的做法。



我的代码:



 <%= link_to下载CSV,vendor_skus_path(format:csv)%> 

<%= select_tagvendor-select,options_from_collection_for_select(@vendors,id,name),include_blank:true,class:vendor-select form-control%>

< table id =vendor-skus-tableclass =table table-striped table-bordered table-hoverdata-source =<%= vendor_skus_path(format::json) %>>
< thead>
< tr>
< th> Name< / th>
< th>供应商< / th>
< th>库存数量< / th>
< / tr>
< / thead>
< tbody>
< / tbody>
< / table>

$('#vendor-select.vendor-select')。on('change',function(){
$('#vendor-skus-table')。DataTable ).ajax.reload();
});

Coffeescript

  $  - > 
$('#vendor-skus-table')。DataTable
处理:true
serverSide:true
检索:true
pagingType:'full_numbers'
ajax:data:(d) - >
d.sku = $('#vendor-skus-table')。data('source')
d.vendor_id = $('#vendor-select')。
返回

可数据

  class VendorSkuDatatable< AjaxDatatablesRails :: Base 
def_delegators:@view,:params,:link_to,:vendor_skus_path,:vendor_path

def sortable_columns
@sortable_columns || = ['VendorSku.name' 'Vendor.name','VendorSku.inventory_quantity']
end

def searchable_columns
@searchable_columns || = ['VendorSku.name','Vendor.name']
end

private

def data
records.map do | record |
[
link_to(record.name,record),
link_to(record.vendor.name,record.vendor),
record.inventory_quantity
]
end
end

def get_raw_records
#insert query here
如果params [:vendor_id] .present?
VendorSku.joins(:vendor).where(vendor_id:params [:vendor_id])
else
VendorSku.joins(:vendor).all
end
end
end

控制器操作

  def index 
@vendor_skus = VendorSku.order(:name)
@vendor_sku = VendorSku.new
@vendors = Vendor.all

respond_to do | format |
format.html
format.csv {send_data @ vendor_skus.to_csv}
format.json {render json:VendorSkuDatatable.new(view_context,{vendor_id:params [:vendor_id]})}
format.xls#{send_data @ vendor_skus.to_csv(col_sep:\t)}
end
end

模型方法

  def self.to_csv(options = {})
CSV.generate(options)do | csv |
csv<<< column_names
all.each do | product |
csv<<< product.attributes.values_at(* column_names)
end
end
end


解决方案

如果您还没有致力于编写自定义服务器端导出的想法,可以简单地添加一个长度菜单。您提到当您使用导出按钮时,它仅导出可见行,但是您尝试允许用户在导出之前更改可见行的数量?这似乎是一个更容易的解决方案,因为它听起来像是想要使用导出按钮。

  $('#example')。dataTable({
lengthMenu:[[10,25,50 ,-1],[10,25,50,全部]]
});

上面的代码块将为要显示的记录数提供4个选项; 10,25,50和所有记录。您可以添加或删除所需的任何分页选项,但在我看来,如果您至少拥有 [ - 1] [所有] 每个数组的一部分,您可以允许用户在导出之前显示所有记录,以将它们全部放在excel文件中。您甚至可以更改excel导出确认窗口,让用户在导出之前知道这一点。


For my app, I have a datatable that uses ajax to retrieve records. The datatable allows the user to sort, search and I have added an extra custom field which allows the users to filter based on a category.

Now, when I use the HTML5 method provided by datatables to export to CSV/Excel, I only get the records that are displayed in the browser in the export. So, my only option is to do a server side export. I have a working export function, but I am struggling to find the proper way to also pass my filters to this export function.

I'm not sure what the best way is to get my parameters to my export method in my model. I thought about including jQuery to add the parameter to my link_to, but I'm not sure how to do this and if this is considered 'good practise'.

My code:

Table

<%= link_to "Download CSV", vendor_skus_path(format: "csv") %>

<%= select_tag "vendor-select", options_from_collection_for_select(@vendors, "id", "name"), include_blank: true, class:"vendor-select form-control" %>   

<table id="vendor-skus-table" class="table table-striped table-bordered table-hover" data-source="<%= vendor_skus_path(format: :json) %>">
  <thead>
    <tr>
      <th>Name</th>
      <th>Vendor</th>
      <th>Inventory Quantity</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

$('#vendor-select.vendor-select').on('change', function() {
  $('#vendor-skus-table').DataTable().ajax.reload();
});

Coffeescript

$ ->
  $('#vendor-skus-table').DataTable
    processing: true
    serverSide: true
    retrieve: true
    pagingType: 'full_numbers'
    ajax: data: (d) ->
      d.sku = $('#vendor-skus-table').data('source')
      d.vendor_id = $('#vendor-select').val();
      return

Datatable

class VendorSkuDatatable < AjaxDatatablesRails::Base
  def_delegators :@view, :params, :link_to, :vendor_skus_path, :vendor_path

  def sortable_columns
    @sortable_columns ||= ['VendorSku.name', 'Vendor.name', 'VendorSku.inventory_quantity' ]
  end

  def searchable_columns
    @searchable_columns ||= ['VendorSku.name', 'Vendor.name']
  end

  private

  def data
    records.map do |record|
      [
        link_to(record.name, record),
        link_to(record.vendor.name, record.vendor),
        record.inventory_quantity
      ]
    end
  end

  def get_raw_records
    # insert query here
    if params[:vendor_id].present?
      VendorSku.joins(:vendor).where(vendor_id: params[:vendor_id])
    else
      VendorSku.joins(:vendor).all
    end
  end
end

Controller action

def index
  @vendor_skus = VendorSku.order(:name)
  @vendor_sku = VendorSku.new
  @vendors = Vendor.all

  respond_to do |format|
    format.html
    format.csv { send_data @vendor_skus.to_csv }
    format.json { render json: VendorSkuDatatable.new(view_context, { vendor_id: params[:vendor_id] }) }
    format.xls # { send_data @vendor_skus.to_csv(col_sep: "\t") } 
  end    
end

Model method

def self.to_csv(options = {})
  CSV.generate(options) do |csv|
    csv << column_names
    all.each do |product|
      csv << product.attributes.values_at(*column_names)
    end
  end
end

解决方案

If you aren't already committed to the idea of writing a custom serverside export, you can simply add a length menu. You mentioned that when you use the export button it exports only the visible rows, but have you tried allowing the user to change the number of visible rows before exporting? That seems like a much easier solution since it sounds like you wanted to use the export button in the first place.

$('#example').dataTable( {
    "lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ]
} );

The above code block will give 4 options for number of records to display; 10, 25, 50, and all records. You can add or remove whatever pagination options you want, but it seems to me that if you at least had the [-1] and the ["All"] part of each array you could allow users to show all records before exporting to get them all in the excel file. You could even change the excel export confirmation window to let the user know to do this before exporting.

这篇关于导出ajax / serverside datatable的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆