基于thinkphp3.2框架
Controller
<?php
namespace Home\Controller;
use Think\Controller;
class LocationController extends Controller{
/**
* 显示首页,只查询省份列表
* @return 无
*/
public function index(){
$pros = M('province')->select();
$this->assign("pros",$pros);
$this -> display();
}
/**
* 查询对应省份的城市列表
* @return 无
*/
public function city() {
$provice = $_POST ['provice'];
$rs = M ( 'location' )->where ('province_id = '.$provice)->select();
if (count ( $rs )) {
$msg = array("status"=>1,"data"=>$rs);
$this->ajaxReturn($msg);
exit();
} else {
$rspro = M ( 'province' )->where ('id='.$provice)->find();
$rs = M ( 'location' )->where ('province_id = '.$provice)->select();
if (count ( $rs )) {
$msg = array("status"=>1,"data"=>$rs);
$this->ajaxReturn($msg);
exit();
} else {
$msg = array("status"=>0,"data"=>"");
$this->ajaxReturn($msg);
exit();
}
}
}
}
view
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="__PUBLIC__/Home/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#province").change(function() {
$.post("{:U('Location/city')}", {
'provice': this.value
}, function(data) {
if (data.status == 1) {
var locations = data.data;
var a = [];
for (var i = 0; i < locations.length; i++) {
var city_val = locations[i]['id'];
var city_name = locations[i]['city'];
a.push("<option value = '" + city_val + "'>" + city_name + "</option>");
}
$("select[name=city]").html("<option value=''>所在区域</option>" + a.join(""));
}
}, 'json');
})
});
</script>
<title>城市列表</title>
</head>
<body>
<div class="location">
<select id="province" name="province">
<option value="">选择省份</option>
<foreach name="pros" item="r">
<option value="{$r.id}">{$r.name}</option>
</foreach>
</select>
<select id="city" name="city">
<option value="">选择城市</option>
</select>
</div>
</body>
</html>