【问题标题】:Dynamic select menus in Rails 3Rails 3 中的动态选择菜单
【发布时间】:2011-09-03 17:13:50
【问题描述】:

我已经阅读了很多关于此的文章,甚至观看了 Railscast,但似乎没有什么适合我的情况。

如何使用 Ajax 请求的结果更新“高度”选择选项?

<%= nested_form_for @estimate do |f| %>

  <%= f.label :date %><br />
  <%= f.text_field :date %><br />
  <%= f.label :job_name %><br />
  <%= f.text_field :job_name %><br />

  <%= f.fields_for :items do |builder| %>
    <%= builder.label :description %><br />
    <%= builder.text_field :description %><br />
    <%= builder.label :material %><br />
    <%= builder.select :material, @letters.map { |l| [l.material, l.material] }, {}, :id => "material_field" %><br />
    <%= builder.label :height %><br />
    <%= builder.select :height, @letters.map { |l| [l.height, l.height] }, {}, :id => "height_field" %><br />
    <%= builder.label :thickness %><br />
    <%= builder.select :thickness, @letters.map { |l| [l.thickness, l.thickness] }, {}, :id => "thickness_field" %><br />

    <%= builder.label :quantity %><br />
    <%= builder.text_field :quantity, :id => "quantity_field" %>
    <%= builder.link_to_remove "Remove this item" %>
  <% end %>

  <%= f.link_to_add "Add a item", :items %>
  <%= f.submit "Add item" %>


<% end %>

<script type="text/javascript">

$("#material_field").change(function() {
    //alert("hello")
    var material = $("#material_field").val();
    $.ajax({
      url: '/estimates/height_options?material=' + material, type: 'get', dataType: 'html',
      processData: false,
      success: function(data) {
        //Not sure what to do here with the returned data
      }
    });    
});

</script>


class EstimatesController < ApplicationController

  def height_options
    @heights = Letter.find_all_by_material(params[:material])
    if @heights.blank?
      render :text => "Record not found"
    else
      render :json => @heights
    end
  end

end

Ajax 请求工作正常,它返回了一个适当的字母数组。我从这里去哪里?我将非常感谢任何人对此的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 jquery


    【解决方案1】:

    在您生成的 html 代码中,您有类似的内容:

    <select id="item_height">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="5">5</option>
      <option value="10">10</option>
      <option value="15">15</option>
      <option value="25">25</option>
    </select>
    

    您可以通过 jQuery 方法将其他选项标记插入到您的选择中。我认为这样的事情可以工作:

    $("#item_height").html($("#item_height").html() + "<option value="50">50</option>")
    

    或者更聪明的东西,但这就是想法。

    【讨论】:

    • 如何循环访问从 Ajax 调用返回的数据?
    • 两个选项:返回的数据正是您要插入的 html 代码(不是很灵活但简单),或者您循环遍历数据。如果要进行此循环,则数据必须是 json 数组(to_json 方法)。你可以使用这个 jquery 方法:api.jquery.com/jQuery.each.
    猜你喜欢
    • 2015-03-03
    • 2012-11-01
    • 2012-06-16
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多