【问题标题】:Fetch items via ajax request on rails通过rails上的ajax请求获取项目
【发布时间】:2015-09-28 14:16:14
【问题描述】:

所以我有选择标签和嵌入​​的选项标签。我在这里得到了帮助,Jquery Filter next select group based on selection of previous select group, 关于如何根据上一个选择组的选择过滤下一个选择组。

在更深层有很多选项,所以我想知道如何使用 ajax 请求来做到这一点。我希望通过 ajax 填充 layer2(和更深层)。

下面是一些玩具 html,同样来自这里,Jquery Filter next select group based on selection of previous select group, 演示如何使用我得到帮助的 jquery 来影响具有前一层的更深的多选框。

<select id="layer1" multiple="multiple">
  <option data-id="3">Chocolate</option>
  <option data-id="5">Cookie</option>
</select>

<select id="layer2" data-depends-on="layer1" multiple="multiple">
  <option data-parent="3" data-id="6">Milk Chocolate</option>
  <option data-parent="5" data-id="7">Sprinkled Cookie</option>
  <option data-parent="5" data-id="8">Iced Cookie</option>
</select>

<script>
$("select").each(function(){
    // cache all options
    $(this).data('options', $('option', this));
}).on('change', function(e){
    var current = this, selected = [];

    // find all selected for the current select and
    // store them in a local variable
    $('option:selected', current).each(function(){
        selected.push($(this).data('id'));
    });

    // find all selects that depend on this one.
    $("select").filter(function(){
        return $(this).data('depends-on') === current.id;
    }).each(function(){
        // search our cached options and filter them
        // by the selected option(s).  Store them in
        // a local variable.
        var children = $(this).data('options').filter(function(){
            return selected.indexOf($(this).data('parent')) > -1;
        });

        // empty and repopulate the select with the
        // filtered results. Also, trigger the next
        // select so the effect cascades.
        $(this).empty().append(children).trigger('change');
    });
}).trigger('change'); // trigger change so it filters
                      // on page load.
                      </script>

这里有一些 Rails 代码和相应的视图,让您了解我是如何使用 Rails 进行操作的。 Rails 代码

  def new
    @one = CategoryLevelOne.all.map { |c| [c.id, c.name] }
    @two = CategoryLevelTwo.all.map { |c| [c.id, c.name] }
  end

对应视图

<%=form_tag('/companies', method: :post)%>
    <select name="category_id[]" id="layer1" multiple="multiple" size="20">
      <%= render 'companies/list/category_one' %>
    </select>
    <select name="category_id2[]" data-depends-on="layer1" id="layer2" multiple="multiple" size="20">
      <%= render 'companies/list/category_two' %>
    </select>
<%= submit_tag%>
 //the same jquery script is used as in the above code

公司/列表/_category_one.html.erb

<% @one.each do |c| %>
  <option data-id=<%=c[0]%>  value=<%=c[1]%>><%=c[1]%></option>
<% end %>

我想做一个 ajax 请求,它对控制器操作执行 GET 请求,获取一个对象,然后使用该对象,在指定的选择标签内创建/更新一堆选项标签。

所以我想它看起来像这样

ajax 请求触发某个控制器动作的某个 GET 请求 在该控制器动作中,它获取某个对象数组,并以 json 的形式返回它。 采用该数组并能够执行类似于

的操作的 javascript
<% @one.each do |c| %>
<option data-id=<%=c[0]%> style="color:<%=c[2]%>" value=<%=c[1]%>><%=c[1]%></option>
<% end %>

对于特定的选择标签。

【问题讨论】:

    标签: javascript jquery html ruby-on-rails ajax


    【解决方案1】:

    在这里,我们使用相应的 id 数据 id 在选择标签更改时对服务器进行 ajax 调用。

    然后从 params[:id] 并从中获取相应的数据,并将此数据动态附加到来自 ajax 成功的另一个 select 标记。 (动态重新创建选项标签。)

    例如。 2 选择标签 - 国家和州

    根据国家/地区的选择,州应该改变。

    请参考下面的代码。

    在视图中:

    <%= f.select :country, @countries, id: "country" %>
    
    <%= f.select :state, @states, id: "state" %>
    

    在 JS 中:

    $("#country").change(function() {
        $.ajax({
          type: "GET",
          contentType: "application/json; charset=utf-8",
          url: "get_states/"+$(this).val(),
          corssDomain: true,
          dataType: "json",
          success: function (data) {
             var listItems = "<option value=''>Select</option>";
             $.each(data,function(key,value){
             listItems+= "<option value='" + value.id + "'>" + value.state_name + "</option>";
             });
             $("#state").html(listItems);
             //alert(JSON.stringify(data));
          },
    
          error : function(data) {
    
          }
       });
     });
    

    在控制器中 -

    def get_states
      country = Country.find_by_id(params[:id])
      if country  
        @states = country.states
        render :json => @states
      end
    end
    

    在路线中 -

    get 'get_states/:id' => 'users#get_states'
    

    希望这个例子会有所帮助。

    【讨论】:

    • 哇不错。你知道我怎么能用一个 id 数组来做到这一点吗?将一个 id 数组发送到控制器。我基本上想获取一堆匹配任何 id 数组的条目。
    • @user3916997 请参考这个问题。 stackoverflow.com/questions/16435895/… 或更好,您可以用逗号分隔一串 id 并通过 ajax 请求,然后在控制器中用逗号分割该字符串并进行进一步处理。
    • @user3916997 如果这个答案对您有帮助,请接受它:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 2013-03-14
    • 1970-01-01
    相关资源
    最近更新 更多