完美实现中国省市区ajax三级联动.
一,下载MYSQL的数据库表 ,分别有三个province city area,
二,在helpers当中加入一个方法,取出全国省:
def get_area_select_options Province.find(:all,:order=>'province').collect{|item|[item.province,item.provinceid]}.insert(0,["请选择..",nil]) end
三,在views当中,比如new的form当中需要加入如下语句:
<p><label for="friend_level2_provice_id">所在城市</label><br/> <%= select("friend_level2", "provice_id", get_area_select_options, {}, { "onchange" => remote_function( :with => "'parent_id='+value", :update => 'next_select', :complete => "Element.hide('county_select')", :url => { :action => :select_with_ajax } ) })%> <span id='next_select'> </span> <span id='county_select'> </span> <br/> </p>
四,分别在对应的controllers当中加入如下语句:
def select_with_ajax @citys = [["请选择",""]]+City.find(:all, :conditions => ["fatherid = ?", params[:parent_id]]).collect { |item| [item.city, item.cityid] } render(:layout => false) end def select_with_ajax1 @areas = Area.find(:all, :conditions => ["fatherid = ?", params[:parent_id]]).collect { |item| [item.area, item.areaid] } render(:layout => false) end
五,在views创建两个rhtml分别是:select_with_ajax,代码如下:
<%= select("friend_level2", "city_id", @citys, {}, { "onchange" => remote_function( :with => "'parent_id='+value", :update => 'county_select', :complete => "Element.show('county_select')", :url => { :action => :select_with_ajax1 } ) })%>
另外一个是select_with_ajax1,代码如下:
<%= select("friend_level2", "area_id", @areas) %>
六,我目的表结构是:
CREATE TABLE `friend_level2s` ( `id` int(10) unsigned NOT NULL auto_increment, `provice_id` int(11) default NULL, `city_id` int(11) default NULL, `area_id` int(11) default NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
另外,如果有乱码请在application.rb当中加入如下语句:
before_filter :configure_charsets def configure_charsets @response.headers["Content-Type"] = "text/html; charset=utf-8" # Set connection charset. MySQL 4.0 doesn’t support this so it # will throw an error, MySQL 4.1 needs this suppress(ActiveRecord::StatementInvalid) do ActiveRecord::Base.connection.execute 'SET NAMES UTF8' end end
使用说明,完美实现了动态查询中国省市区的联动!呵呵,好好学习.