2011-09-03 157 views
0

我一直在閱讀大量關於這方面的文章,甚至觀看了Railscast,但似乎沒有什麼符合我的情況。Rails 3中的動態選擇菜單

如何使用我的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請求正常工作,它返回相應字母的數組。我從哪裏出發?我會很感激任何人的幫助。

回答

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>") 

或者更聰明的東西,但這是主意。

+0

如何循環從Ajax調用返回的數據? –

+0

有兩種選擇:返回的數據正好是你想要插入的html代碼(不是非常靈活但很簡單),或者你循環數據。如果你想做這個循環,你的數據必須是一個json數組(to_json方法)。你可以使用這個jquery方法:http://api.jquery.com/jQuery.each/。 –