省市区三级联动

这个代码是纯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');
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值