自己在项目中遇到的问题,默认加载三级联动不成功。
在网上找了很多文章,都没有满足需求。
直接上代码,亲测成功,写得不好的,还请指教。
thinkphp 框架中使用 ,使用页面 .tpl
<tr>
<th width="10%">地区 :</th>
<td>
<select name="province_id" id="province_id" onchange="loadRegion('province_id',{$info.cemetery.province_id},2,'city_id','{:U('china/getRegion')}',{$info.cemetery.city_id});clear_id('city_id');clear_id('area_id');">
<option value="0" selected>省份/直辖市</option>
<volist name="province" id="vo">
<option value="{$vo.id}" >{$vo.name}</option>
</volist>
</select>
<select name="city_id" id="city_id" onchange="loadRegion('city_id',{$info.cemetery.city_id},3,'area_id','{:U('china/getRegion')}',{$info.cemetery.area_id});clear_id('area_id');">
<option value="0">市/县</option>
</select>
<select name="area_id" id="area_id">
<option value="0">镇/区</option>
</select>
</td>
</tr>
$(function() {
$('#province_id').val({$info.cemetery.province_id});
$('#province_id').trigger("change");
$('#city_id').val({$info.cemetery.city_id});
$('#city_id').trigger("change");
$('#area_id').val({$info.cemetery.area_id});
$('#area_id').trigger("change");
});
function clear_id(id){
$('#'+id).empty();
jQuery("<option value=0>请选择</option>").appendTo(jQuery("#"+id));
}
function loadRegion(sel,parent_id,type_id,selName,url,value){
jQuery("#"+selName+" option").each(function(){
jQuery(this).remove();
});
jQuery("<option value=0>请选择</option>").appendTo(jQuery("#"+selName));
if(parent_id==0 || parent_id==""){
parent_id=jQuery("#"+sel).val();
}
if(jQuery("#"+sel).val()!=0 && jQuery("#"+sel).val()!="" && jQuery("#"+sel).val()!=parent_id)
{
parent_id=jQuery("#"+sel).val();
}
if(parent_id==0){
return;
}
if(value==0){
value=-99;
}
jQuery.getJSON(url,{pid:parent_id,type:type_id},
function(data){
if(data){
jQuery.each(data,function(idx,item){
jQuery("<option value="+item.id+""+ (value==item.id?" selected":"") +">"+item.name+"</option>").appendTo(jQuery("#"+selName));
});
}else{
jQuery("<option value='0'>请选择</option>").appendTo(jQuery("#"+selName));
}
}
);
}
使用页面的控制器 Action.class.php
public function _before_edit()
{
$province = D('china')->where ( array('pid'=>1) )->select ();
$this->assign('province',$province);
}
ajax 获取下级列表,城市 Action.class.php
class chinaAction extends BackendAction{
public function _initialize(){
parent :: _initialize();
$this->_name = 'china';
$this -> _mod = D('china');
}
public function index(){
$province = $this -> _mod->where ( array('pid'=>1) )->select ();
$this->assign('province',$province);
$this->display();
}
public function getRegion(){
$map['pid']=$_REQUEST["pid"];
$map['type']=$_REQUEST["type"];
$list=$this -> _mod->where($map)->select();
echo json_encode($list);
}
}
运行截图:
全国最新城市(省、市、区) .sql 下载地址