繁体   English   中英

meta_search +数据表

[英]meta_search + datatables

我在Rails 3.1应用程序中使用数据表。 数据表设置为在服务器端工作。 我正在使用ajax请求从服务器获取数据,然后将其显示在表中。

我使用meta_search作为过滤器来从数据库中获取数据。

这是我认为的代码:

= simple_form_for @search, :url => offer_coupons_path(@offer), :html => {:method => :get} do |f|
= f.select :redeemed_equals,  [['All Coupons', '']] + [["Redeemed", true], ["Not Redeemed", false]]

这是控制器中的方法:

def offer_coupons_list
  search_params = params[:search] || {"meta_sort"=>"user_full_name.asc"}
  @search = Coupon.search(search_params)
  @coupons = @search.includes(:user).includes(:order => :gift).page(@page)
  render :partial => 'coupons/offer_coupons_list'
end

这是负责将ajax请求发送到服务器的javascript:

$("#search_redeemed_equals").change(function(e){
    table = $("#grid").dataTable();
    var data = $("#search_redeemed_equals").parents("form:first").serialize();
    $.ajax({
        'url': 'coupons/offer_coupons_list',
        'data': data,
        'type': 'POST'
    });
    table.fnDraw();
    e.preventDefault();
});

问题是该脚本将两个ajax请求发送到服务器。 第一个请求正确,并返回过滤的数据。 调用fnDraw()时会发送另一个请求,并返回未过滤的数据。 因此,表中的数据不会更改。 每次调用任何数据表功能时,都会发送请求。 我该如何解决这个问题?

我认为问题在于您正在初始化事件处理程序中的表,因此您两次调用服务器。

$("#search_redeemed_equals").change(function(e){
    table = $("#grid").dataTable();//one call to the server and you use a global variable!
    var data = $("#search_redeemed_equals").parents("form:first").serialize();
    $.ajax({
        'url': 'coupons/offer_coupons_list',
        'data': data,
        'type': 'POST'
    });
    table.fnDraw();//second call
    e.preventDefault();
});

我认为你应该把骨化

var table = $("#grid").dataTable();

$("#search_redeemed_equals").change(function(e){
    table = $("#grid").dataTable();//one call to the server and you use a global variable!
    var data = $("#search_redeemed_equals").parents("form:first").serialize();
    $.ajax({
        'url': 'coupons/offer_coupons_list',
        'data': data,
        'type': 'POST'
    });
    table.fnDraw();//second call
    e.preventDefault();
});

如果您已经在页面的另一部分中初始化了表格,只需将表格分配给javascript变量,然后在该变量上调用fnDraw

暂无
暂无

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

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