我正在尝试构建一个动态菜单,因此当用户选择一个国家/地区时,状态菜单会更新。
我正在查看我的开发日志,我看到该操作运行 db 查询,然后呈现 json.erb 文件,但我无法从浏览器获得任何响应。
这是我所拥有的:
控制器/settings_controller.rb
respond_to :html, :json
def getstates
@states = Country.find_by_iso(params[:account][:addresses_attributes]["0"][:country]).states
respond_with(@states)
end
(注意:表单是嵌套表单,这就是为什么 params 哈希这么长。)
设置/edit.html.erb
<%= address.collection_select :country, Country.order(:name), :iso, :name, {:include_blank => true}, "data-remote" => true, "data-url" => "/settings/getstates", "data-type" => :json %>
<%= address.select :state, [], {:include_blank => true}, :disable => true %>
设置/getstates.json.erb
$(document).ready(function() {
$("#account_addresses_attributes_0_country").bind('ajax:success', function(evt, data, status, xhr){
var select = $('#account_addresses_attributes_0_state');
if (data !== null) {
select.removeAttr('disabled');
$.each(data, function(key, value) {
$("<option/>").val(value[1]).text(value[0]).appendTo(select);
});
} else {
select.empty();
select.attr('disabled', 'disabled');
}
});
});
(注意:我从http://blog.madebydna.com/all/code/2011/12/05/ajax-in-rails-3.html获得此代码)
开发日志
Processing by SettingsController#getstates as JSON
Parameters: {"account"=>{"addresses_attributes"=>{"0"=>{"country"=>"UY"}}}}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", "1"]]
Country Load (0.2ms) SELECT "countries".* FROM "countries" WHERE "countries"."iso" = 'UY' LIMIT 1
Rendered settings/getstates.json.erb (0.3ms)
Completed 200 OK in 3ms (Views: 1.5ms | ActiveRecord: 0.3ms)
这是我在开发日志中看到的输出。但在浏览器中什么都没有。我尝试添加警报和控制台日志方法,但没有。
如果有人能帮助我理解我做错了什么,我将不胜感激。