使用卡門寶石:https://github.com/jim/carmen。
我以前做過以下(AJAX)。
HTML:
<p>
<label>Country <span>*</span></label>
<%= profile_form.select(:country,Carmen.countries, {:include_blank => 'Select a Country'}, :id => "profile_country") %>
</p>
<p>
<label>State <span>*</span></label>
<%= profile_form.select(:state, "" , {:include_blank => 'Select a Country first'}, :id => "profile_state") %>
</p>
控制器:
def states
begin
render :json => Carmen::states(CGI::unescape(params[:country]))
rescue
render :json => {"content" => "None"}.to_json
end
end
的Javascript使用jQuery:
$('#profile_country').change(function() {
if ($(this).val() == '')
{
$('#profile_state').empty();
$('#profile_state').append($('<option>No state provided for your country</option>'));
}
else {
$.ajax({
type: "GET",
url: "/remote/get_states/" + encodeURIComponent($(this).attr('value')),
success: function(data){
if (data.content == 'None')
{
$('#profile_state').empty();
$('#profile_state').append($('<option>No state provided for your country</option>'));
}
//handle the case where no state related to country selected
else
{
$('#profile_state').empty();
$('#profile_state').append($('<option>Select your State</option>'));
jQuery.each(data,function(i, v) {
$('#profile_state').append($('<option value="'+ data[i][1] +'">'+data[i][0] +'</option>'));
});
}
}
});
}
});
爲了誰也許不知道爲什麼上面的代碼是不工作的用戶,請加JS在$(document).ready(function(){......});塊 – 2011-10-24 02:32:16