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請求正常工作,它返回相應字母的數組。我從哪裏出發?我會很感激任何人的幫助。
如何循環從Ajax調用返回的數據? –
有兩種選擇:返回的數據正好是你想要插入的html代碼(不是非常靈活但很簡單),或者你循環數據。如果你想做這個循環,你的數據必須是一個json數組(to_json方法)。你可以使用這個jquery方法:http://api.jquery.com/jQuery.each/。 –