我有一个 ajax 请求,负责获取所选州的一些城市。所以,我有一个使用 simple_form 的表单和两个选择,州和城市,如下所示:
我不知道如何替换城市选择的城市。我就是这样做的:
Controller ajax method
def by_state
cities = City.by_state params["state"]
render :json => { :cities => cities }
end
Form
<%= simple_form_for @store, :html => { :class => 'store-filter' } do |f| %>
<table align="center" cellspacing="10" cellpadding="2">
<tr>
<th colspan="2">Store list</th>
</tr>
<tr>
<td>State:</td>
<td>
<%= f.input :state, :collection => State.all, :include_blank => false, :label => false, :input_html => { :id => "state", :name => "state" } %>
</td>
</tr>
<tr>
<td>City:</td>
<td>
<%= f.input :city, :collection => City.find(:all, :conditions => { :state_id => 1 }), :include_blank => false, :label => false, :input_html => { :id => "city", :name => "city" } %>
</td>
</tr>
.
.
.
Ajax
$("#state").change(function() {
var state_id = $(this).val();
$.ajax({
type: "GET",
url: "cities/state/"+state_id,
success: function(data) {
console.log(data); //returns Object with Array of Cities
$("#city").html(data["cities"]); //replaces to nothing city select
}
});
});
因此,当我选择一个州时,城市选择被 null 取代。为什么?谢谢!