PLease帮助,我用了一些例子来构建动态选择,但它似乎不起作用,不过在控制台我可以看到200状态,我不流利所以请请帮忙,问题是选择中的列表会不减少,选择previos后显示相同的选项
index.html.erb
<%= collection_select(nil, :site_id, @sites, :id, :name, {:prompt => "Select a Site"}, { :id => "sites_select"}) %>
<br/>
<%= collection_select(nil, :floor_id, @floors, :id, :name, {:prompt => "Select a Floor"}, {:id => "floors_select"}) %>
<br/>
<%= collection_select(nil, :pod_id, @pods, :id, :name, {:prompt => "Select a pod"}, {:id => "pods_select"}) %>
<script>
$(document).ready(function() {
$('#sites_select').change(function() {
$.ajax({
url: "<%= update_floors_path %>",
data: {
site_id : $('#sites_select').val()
},
dataType: "script"
});
});
$('#floors_select').change(function() {
$.ajax({
url: "<%= update_pods_path %>",
data: {
floor_id : $('#floors_select').val()
},
dataType: "script"
});
});
});
</script>
devices_controller.rb
def update_floors
# updates floors and pods based on genre selected
site = Site.find(params[:site_id])
# map to name and id for use in our options_for_select
@floors = site.floors.map{|a| [a.name, a.id]}.insert(0, "Select a Floor")
@pods = site.pods.map{|s| [s.name, s.id]}.insert(0, "Select a Pod")
end
def update_pods
# updates pods based on floor selected
floor = Floor.find(params[:floor_id])
@pods =floor.pods.map{|s| [s.name, s.id]}.insert(0, "Select a Pod")
end
update_floors.js.erb
$('#floors_select').html("<%= escape_javascript(options_for_select(@floors)) %>");
$('#pods_select').html("<%= escape_javascript(options_for_select(@pods)) %>");
update_pods.js.erb $('#pods_select')。html(“&lt;%= escape_javascript(options_for_select(@pods))%&gt;”);
的routes.rb
get 'devices/update_floors', :as => 'update_floors'
get 'devices/update_pods', :as => 'update_pods'
root :to => "devices#index"
感谢任何建议 谢谢, d
答案 0 :(得分:1)
问题出在您的控制器上,
你还没有提到response_to js阻止代码中的任何位置,
只需将此代码放入两种更新方法中,
respond_to do |format|
format.js
end
答案 1 :(得分:1)
似乎新加载的JavaScript没有向父页面添加效果。为什么不在Ajax成功回调中使用$()。html。并使update.js.html页面仅包含select的选项。应该工作。
的javascript:
$("#sites_select").change(function(){
$.ajax({
url: your_url,
//orther options ...
success: function(data){
$("#floors_select").html(data);
}
});
});
并在您的update_floors.js.html
中<%=options_for_select(@floors)%>
对更新窗格执行相同操作。 :)
答案 2 :(得分:0)
在控制器respond_to :js, :only=>[:update_floors,:update_pods ]
中给出响应格式
除此之外,将以下内容写入update_floors.js.erb
文件。
$('#floors_select').html("<%= escape_javascript(collection_select(:your_object_name, :floor_id, @floors.to_a, :id, :name, :prompt=>"Select a Floor")) %>");
我认为上述情况会奏效。