意见:
= select_tag(:district,"<option value='0'>#{t('Please select district')}</option>".html_safe+options_from_collection_for_select(District.all, "id", "title"),:'data-remote' => 'true',:'data-url' => url_for(:controller => 'select', :action => 'getdata'),:'data-type' => 'json')
= select_tag(:state,"<option value='0'>#{t('Please select state')}</option>".html_safe,:'data-remote' => 'true',:'data-url' => url_for(:controller => 'select', :action => 'getdata'),:'data-type' => 'json')
= select_tag(:city,"<option value='0'>#{t('Please select city')}</option>".html_safe)
:javascript
$(document).ready(function() {
$('#district').live('ajax:success', function(evt, data, status, xhr) {
var selectbox2 = $('#state');
selectbox2.empty();
var opt = $('<option/>');
opt.attr('value', "0");
opt.text("#{t('Please select state')}");
opt.appendTo(selectbox2);
$.each(data, function(index, value) {
var opt = $('<option/>');
opt.attr('value', value[0]);
opt.text(value[1]);
opt.appendTo(selectbox2);
});
var selectbox3 = $('#city');
selectbox3.empty();
var opt = $('<option/>');
opt.attr('value', "0");
opt.text("#{t('Please select city')}");
opt.appendTo(selectbox3);
});
$('#state').live('ajax:success', function(evt, data, status, xhr) {
var selectbox3 = $('#city');
selectbox3.empty();
$.each(data, function(index, value) {
var opt = $('<option/>');
opt.attr('value', value[0]);
opt.text(value[1]);
opt.appendTo(selectbox3);
});
});
});
控制器:
class SelectController < ApplicationController
def getdata
@data_for_select1 = params[:district]
if @data_for_select1
@data_for_select2 = State.where(:district_id => @data_for_select1).all
render :json => @data_for_select2.map{|c| [c.id, c.title]}
else
@data_for_select1 = params[:state]
@data_for_select2 = City.where(:state_id => @data_for_select1).all
render :json => @data_for_select2.map{|c| [c.id, c.name]}
end
end
end
路线:
get 'assets' => 'select#getdata'
注意:你必须有一个本地化使用的短语,否则js不起作用