ruby on rails 城市三级联动查询json

来源:互联网 发布:贝贝看图软件 编辑:程序博客网 时间:2024/05/18 00:55


http://www.helloweba.com/demo/cityselect/js/city.js

 

#首先我们要定义一个tools(这个tools是为了将数据插入到数据库)

class Tool < ActiveRecord::Base

def self.init_province_city_and_town

 require 'httparty'     

# 定义URL              
url = "http://www.helloweba.com/demo/cityselect/js/city.js"
response = HTTParty.get url

#puts "======== #{response.body} ==========="

 # 获取 到结果          
items = JSON.parse(response.body) rescue []
Province.transaction do
return if items.blank?
       items['citylist'].each do |province|
         province_name = province['p']   
         @province = Province.create :name => province_name
         Rails.logger.info "province ==!!!!==!!!!!== #{province_name}"

         next if province['c'].blank?    

         City.transaction do
           province['c'].each do |city|    
             city_name = city['n']           
              @city = City.create :name => city_name, :province_id => @province.id
              Rails.logger.info "city ======== #{city_name}"
              next if city['a'].blank?        
              Town.transaction do
                city['a'].each do |town|        
                  town_name= town['s']            
                  @town = Town.create :name => town_name, :city_id => @city.id 
                  Rails.logger.info "town ======== #{town_name}"
                end
              end
            end
          end
        end
      end
    end
  end

bundle

创建三张表(省,市,县)

在控制台输入Tool.init_province_city_and_town将字段加入表中

  <%= form_for @address do |f|%>
     <%= select_tag :province, options_from_collection_for_select(Province.all, :id, :name), {:include_blank=>"请选择省份"} %>
     <%= select_tag :city, options_from_collection_for_select([], :id, :name), {:include_blank=>"请选择城市"} %>
     <%= select_tag :town, options_from_collection_for_select([], :id, :name), {:include_blank=>"请选择乡镇"} %>
     <%= f.submit '提交' %>
   <% end %>
   
   <script>
     $( "#province" ).change(function() {
      if ($(this).val()){
        get_cities_by_province_id($(this).val());
      }
    });
  
    function get_cities_by_province_id (province_id) {
        console.info('我选择了province')
        console.info(province_id)
        $.ajax({
            type:'get',
            url:'/addresses/get_cities_by_province_id?province_id=' + province_id,
            success:function(data){
                cities = data.cities;
                city_html = ""
                for(var i=0;i<cities.length;i++){
                    city_html += "<option value='" + cities[i].id + "'>" + cities[i].name+ "</option>";
                }
                $("#city").html(city_html);
                $("#town").html("");
            },
            error:function(){
                alert("fail!");
            }
        });                  
  
    }
 

 $( "#city" ).change(function() {
 :     if ($(this).val()){
        get_towns_by_city_id($(this).val());
      }
   });
  
    function get_towns_by_city_id (city_id) {
        console.info('我选择了city')
        console.info(city_id)
        $.ajax({
            type:'get',
            url:'/addresses/get_towns_by_city_id?city_id=' + city_id,
            success:function(data){
                towns = data.towns;
                town_html = ""
               for(var i=0;i<towns.length;i++){
                    town_html += "<option value='" + towns[i].id + "'>" + towns[i].name+ "</option>";
                }
                $("#town").html(town_html);
            },
            error:function(){
                alert("fail!");
            }
        });
  
    }
  
  </script>
 

1 0
原创粉丝点击