
实现原理:根据省份值的变动,通过jQuery把sf_id传给后台php文件处理,php通过查询MySQl数据库,得到对应的地市名,并返回JSON数据给前端处理,即实现联动效果!
为便于讲解,这里直接给出省份:河南省(sf_id=1) 浙江省(sf_id=2),而地市和学生信息则分别建立两张数据表!编码方式均为:utf8!新建数据库并执行以下SQL语句!
代码如下:
/* 地市表 */
create TABLE IF NOT EXISTS `dishi`(
`ds_id` int(3) auto_increment not null primary key,
`sf_id` int(3) not null default '0',
`ds_name` varchar(50) not null
);
/* 学生表 */
create TABLE IF NOT EXISTS `xuesheng`(
`xs_id` int(3) auto_increment not null primary key,
`ds_id` int(3) not null default '0',
`xs_name` varchar(50) not null
);接着搭个前台架子:
代码如下:
接着就是jQuery部分,详解可看代码后注释部分:
代码如下:
function getVal(){
$.getJSON("select.php",{sf_id:$("#sf_id").val()},function(json){
var ds_id = $("#ds_id");
$("option",ds_id).remove(); //清空原有的选项,也可使用 ds_id.empty();
$.each(json,function(index,array){
var option = "
";
ds_id.append(option);
});
});
}
//下面是页面加载时自动执行一次getVal()函数
$().ready(function(){
getVal();
$("#sf_id").change(function(){//省份部分有变动时,执行getVal()函数
getVal();
});
});
script>
其中的select.php就是关键部分了,此文件接收前台通过$.getJSON方法传递过来的参数 sf_id,然后select.php根据省份sf_id获取对应的地市数据,再返回JSON数据,前台通过jQuery将JSON数据进行处理,写入