本文实例讲述了thinkPHP实现的省市区三级联动功能。分享给大家供大家参考,具体如下:
一张表实现省市区三级联动【3409条数据】
1. php代码:
1
2
3
4
5
6
7
8
9
10
11
12
|
public function index(){
$province = M( 'Tree' )->where ( array ( 'pid' =>1) )->select ();
$this ->assign( 'province' , $province );
$this ->display();
}
public function getRegion(){
$Region =M( "Tree" );
$map [ 'pid' ]= $_REQUEST [ "pid" ];
$map [ 'type' ]= $_REQUEST [ "type" ];
$list = $Region ->where( $map )->select();
echo json_encode( $list );
}
|
2. HTML代码:
1
2
3
4
5
6
7
8
9
10
|
< select name = "province" id = "province" onchange = "loadRegion('province',2,'city','{:U('Index/getRegion')}');" >
< option value = "0" selected>省份/直辖市</ option >< volist name = "province" id = "vo" >
< option value = "{$vo.id}" >{$vo.name}</ option ></ volist >
</ select >
< select name = "city" id = "city" onchange = "loadRegion('city',3,'town','{:U('Index/getRegion')}');" >
< option value = "0" >市/县</ option >
</ select >
< select name = "town" id = "town" >
< option value = "0" >镇/区</ option >
</ select >
|
3. javascript代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
function loadRegion(sel,type_id,selName,url){
jQuery( "#" +selName+ " option" ).each( function (){
jQuery( this ).remove();
});
jQuery( "<option value=0>请选择</option>" ).appendTo(jQuery( "#" +selName));
if (jQuery( "#" +sel).val()==0){
return ;
}
jQuery.getJSON(url,{pid:jQuery( "#" +sel).val(),type:type_id},
function (data){
if (data){
jQuery.each(data, function (idx,item){
jQuery( "<option value=" +item.id+ ">" +item.name+ "</option>" ).appendTo(jQuery( "#" +selName));
});
} else {
jQuery( "<option value='0'>请选择</option>" ).appendTo(jQuery( "#" +selName));
}
}
);
}
|
4. SQL代码:
1
2
3
4
5
6
7
8
|
DROP TABLE IF EXISTS `tp_tree`;
CREATE TABLE `tp_tree` (
`id` int (5) unsigned NOT NULL AUTO_INCREMENT,
`pid` int (5) unsigned NOT NULL DEFAULT '0' ,
` name ` varchar (120) DEFAULT NULL ,
`type` tinyint(1) DEFAULT '2' ,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3410 DEFAULT CHARSET=utf8;
|
5. TP_tree.sql文件点击此处本站下载。
希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。