【问题标题】:simple_form select collection populated by AJAX call由 AJAX 调用填充的 simple_form 选择集合
【发布时间】:2016-07-05 11:37:54
【问题描述】:

在我看来,我有一个包含两个选择列表的简单表单:

<%= simple_form_for @job, url: jobs_path do |f| %>
  <%= f.input_field :types, as: :select, collection: @types, id 'types-select' %>
  <%= f.input_field :subtypes, as: :select, collection: @subtypes %>
<% end %>

当用户从第一个列表中选择一个选项时,下面的第二个列表应根据上述选择填充数据库中的值。

因此,当用户从第一个列表中选择一个选项时,我会发出 ajax 请求:

$('#types-select').change(function(){
  $.ajax({
    url: '/subtypes',
    dataType: 'json',
    type: 'GET',
    data: {
      type_id: this.value
    },
    success: function(data) {
      console.log(data);
    }
  });
});

控制器如下所示:

class SubtypesController < ApplicationController
  respond_to :json

  def index
    @subtypes = Type.find(params[:type_id]).subtypes
    render json: @subtypes
  end
end

此时,如何使用 @subtypes 中的选项填充第二个选择?

【问题讨论】:

    标签: ruby-on-rails ajax ruby-on-rails-4 select simple-form


    【解决方案1】:

    您可以在success 回调中填充第二个下拉列表。确保@subtypes 也以正确的 json 格式返回。

    控制器:

      def index
        @subtypes = Type.find(params[:type_id]).subtypes
        render json: @subtypes.map { |item| { value: item.value } }  
      end
    

    JS:

      $.ajax({
        url: '/subtypes',
        dataType: 'json',
        type: 'GET',
        data: {
          type_id: this.value
        },
        success: function(data) {
          // Populate second dropdown here
          var output = '';
          $subtypes.empty().append(function() {
            data.forEach(function(item) {
               output += "<option>" + item.value + "</option>"
            });
            return ouput;
          });
        }
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      相关资源
      最近更新 更多