这个代码是纯js代码,要卸载script标签中,且要有数据库的支持,并且还要有getdata.php文件,在getdata.php中连接数据库,将ajax传来的pid传进来,从数据库中将pid为传来的pid相等的子分类全部查出来,返回给ajax
var pro=$('#pro');
var city=$('#city');
var town=$('#town');
//将数据库中的数据取出来放到省份的下拉表中
//实例化ajax
$.post('getdata.php','',function(d){
var res=JSON.parse(d);
$(pro).html('<option value="0">请选择..</option>');
for(var i=0;i<res.length;i++){
var opt=document.createElement('option');
$(opt).html(res[i]['name']);
$(opt).attr('value',res[i]['id']);
pro.append(opt);
}
},'text');
//为省份的选取绑定change事件
$(pro).change(function(){
var pid=$(this).val();
//实例化ajax
$.post('getdata.php','pid='+pid,function(d){
var res=JSON.parse(d);
$(city).html('<option value="0">请选择..</option>');
for(var i=0;i<res.length;i++){
var opt=document.createElement('option');
$(opt).html(res[i]['name']);
$(opt).attr('value',res[i]['id']);
$(city).append(opt);
}
},'text');
});
//为市区的改变绑定事件
$(city).change(function(){
var pid=$(this).val();
//实例化ajax
$.post('getdata.php','pid='+pid,function(d){
var res=JSON.parse(d);
$(town).html('<option value="0">请选择..</option>');
for(var i=0;i<res.length;i++){
var opt=document.createElement('option');
$(opt).html(res[i]['name']);
$(opt).attr('value',res[i]['id']);
town.append(opt);
}
},'text');
});