利用jquery和ajax实现省市区的三级联动


利用jquery和ajax实现省市区的三级联动

分享一段4年前的代码,偶然间看到了,不嫌弃的可以拿走,哈哈~~~

思路:首先获取默认的省数据,然后根据省的变动获取对应的市数据,最后再根据市的变动来获取对应的区数据

1、jquery代码

 1 

2、html页面

 1 <center>
 2     <h3>利用jquery和ajax实现省市区的三级联动h3>
 3     省:<select id="sheng">
 4         <option>--请选择省--option>
 5         <?php
 6             //遍历数组动态添加option
 7             foreach ($shengs as $sheng) {
 8                 echo "";
 9             }
10         ?>
11     select>
12     市:<select id="shi">
13         <option>--请先选择省--option>
14     select>
15     区:<select id="qu">
16         <option>--请先选择省--option>
17     select>
18 center>

3、php代码

 1 require '../model/UsersModel.class.php';
 2  class UsersController extends BaseController{
 3      private $userModel;
 4      //对userModel进行赋值
 5      public  function __construct() {
 6          $this->userModel=new UserModel();
 7          parent::__construct();
 8      }
 9      //默认主页
10      public function index(){
11          $shengs=$this->userModel->getAllShengs();
12          include '../view/SanJiLianDong.php';
13      }
14      //根据省来显示市
15      public function getShiBySheng(){
16         $shengId=$_GET['shengId'];
17         $shis=  $this->userModel->getShiBySheng($shengId);
18         //返回编码后的城市数组,将php的数组转换成json返回
19         echo json_encode($shis);
20      }
21      public function getQuByShi(){
22         $shiId=$_GET['shiId'];
23         $qus=  $this->userModel->getQuByShi($shiId);
24         //返回编码后的城市数组,将php的数组转换成json返回
25         echo json_encode($qus);
26      }
27  }
28  
29  $UsersController = new UsersController();
30  $action=  empty($_GET['action'])?"index":$_GET['action'];
31  $UsersController->$action();