视图层
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>省市三级联动</title>
</head>
<!-- 因为在框架中,所以是从根目录下请求的,也就是当前目录是index.php所在的目录 -->
<script src="./jquery/jquery.1.12.js"></script>
<body>
<form action="">
<select name="region" id="">
<option value="0">请选择...</option>
<?php foreach ($data as $key => $val): ?>
<option value="<?= $val['region_id']?>"><?= $val['region_name']?></option>
<?php endforeach ?>
</select>
</form>
</body>
</html>
<script>
$(function(){
$(document).on('change',':input[name="region"]',function(){
//获取当前对象select 标签
var _this=$(this);
//获取值
var region_id=_this.val();
//ajax请求的地址
var url="index.php?r=demo/citylist";
//清除当前对象变化时,后面的标签
_this.nextAll().remove();
//如果是请选择就不用请求了
if(region_id==0){
return false;
}
$.get(url,{'region_id':region_id},function(data){
//判断是不是最后一级
if(data.length==0){
return false;
}
//拼接字符串
var str='<select name="region"><option value="0">请选择...</option>';
$.each(data,function(k,v){
str+='<option value='+v.region_id+'>'+v.region_name+'</option>';
})
str+='</select>';
//追加到后面
_this.after(str);
},'json');
})
})
</script>
控制器层
/**
* 省市三级联动
*
*/
public function actionCity(){
$sql="select * from ecs_region where parent_id='0'";
$data=yii::$app->db->createCommand($sql)->queryAll();
return $this->render('city',['data'=>$data]);
}
/**
* 省市三级联动 ajax请求的方法
*
*/
public function actionCitylist(){
//接值 父id
$parent_id=yii::$app->request->get('region_id');
// $parent_id=1;
$sql="select * from ecs_region where parent_id='$parent_id'";
$res=yii::$app->db->createCommand($sql)->queryAll();
// print_r($res);
return json_encode($res);
// echo json_encode($res); 也是可以的
}