数据库添加需要的省份和城市名
index
/**
* 查询管理员的省份
* @author liuz
*/
public function selProvince() {
$Area = M ( 'area' );
$selCity = array ();
$selPro = $Area->distinct ( true )->field ( 'province' )->select ();
$this->assign ( 'selPro', $selPro );
}
/**
* 查询管理员的城市
* @author liuz
*/
public function selCity() {
$Area = M ( 'area' );
$selPro = $_POST ['pro'];
$data ['error'] = "";
$condition ['province'] = $selPro;
$city = $Area->where ( $condition )->field ( 'city' )->select ();
$count = count ( $city );
$data ['count'] = $count;
$data ['city'] = array ();
if ($city == null || $city <= 0) {
$data ['error'] = "数据不存在~~!";
} else {
foreach ( $city as $c ) {
array_push ( $data ['city'], $c ['city'] );
}
}
$this->ajaxReturn ( $data );
}
页面
<div class="col-sm-8">
<select name="province" id="province">
<option value="">请选择省份</option>
<volist name="selPro" id="pro">
<option value="{$pro['province']}">{$pro['province']}</option>
</volist>
</select>
<select name="city" id="city">
<option value="">请选择城市</option>
</select>
</div>
该页面做ajax
<script>
$(document).ready(function(){
//一级分类联动二级分类
$("#province").change(function(){
var pro=$(this).val();
$.ajax({
type: 'POST',
dataType:'json',
url:"{:U('index/selCity')}",
data:"pro="+pro,
success :function(data){
$('#city').empty();
$('#city').append("<option value=''>请选择城市</option>");
for(var i=0;i < data.city.length;i++){
$('#city').append("<option value='"+data.city[i]+"'>"+data.city[i]+"</option>");
}
},
error:function(data){
alert(data.error);
},
});
});
});
</script>