这是一个关于省份和城市的级联操作,当选择省份的时候,省份的状态发生改变,调用provincechange()函数,取得省份ID,并调用application.js的ajax代码,将省份id送到city控制器中,取得所在省份的所有城市并返回,showResponse()函数接受返回结果,并将城市属性结果发送到city.rhtml由provincechange()函数接收,进行相应的显示
ruby 代码
这是 city_controller.rb
def cityByprovince province_id = params[:province_id ] @cities = City.find(:all ,:conditions =>["province_id = ?", province_id ],:order => "orderby") render :text => @bacities.to_json end def index @provinces = Province.find(:all) end
js 代码
application.js
//省份城市级联 function chinacity(province_id,citycon){ var showResponse=function(transport) { var json = eval(transport.responseText); $(citycon).options.length=1; for(var i=0;i var oNewNode=new Option(); oNewNode.value=json[i].attributes.id; oNewNode.text=json[i].attributes.city; $(citycon).options.add(oNewNode); } } var myAjax = new Ajax.Request( '/city/cityByprovince', { method: 'get', requestHeaders:{Accept:'application/json'}, parameters:'province_id='+province_id, onComplete: showResponse } ); }
xml 代码
这是 city.rhtml
<td>省份td> <td> <%= select("user",'province_id',@provinces.collect{|p|[p.province,p.id]},options = {:include_blank => true},html_options = {:onchange =>"provincechange()"}) %> td> <td>城市:td> <td> <%= select("user",'city_id',options = {:"--请选择"=>"0"}) %> td> <script type="text/javascript"> provincechange=function() { chinacity($("user_province_id").value,"user_city_id");
} </script>
} </script>