2013-03-04 53 views
0

我有一個ajax請求負責獲取所選狀態的一些城市。所以,我有一個表單,使用simple_form和兩個選擇,州和城市,如下所示:如何在simple_form select中設置ajax響應?

我不知道如何取代城市選擇的城市。我就是這麼做的:

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 
    } 
    }); 
}); 

所以,當我選擇一個狀態時,城市select被替換爲null。爲什麼? 謝謝!

回答