Ajax 省市二级联动(主要代码)

JS:

var teX=document.getElementsByClassName("text")[0];//获取两个select
var teT=document.getElementById("city");
gePot("get","province.json",true,"",function(rep){//引用封装的方法获取json的值
    arrJson=JSON.parse(rep);
    for (i in arrJson){
        teX.innerHTML+=`<option οnclick='fn(this)' value="">${arrJson[i].name}</option>`;//在第一个select标签中插入省份
    }
});
    gePot("get","city.json",true,"",function(rep){
      arrJSon=JSON.parse(rep);
});
function fn(that){ //第一select标签的点击事件
    for(x in arrJson){
        if(that.innerText==arrJson[x].name){//当选中的文本与province内的name值相等时
            for(y in arrJSon){
                if(arrJson[x].id==y){//当province的id值与city遍历的y值相等时
                    teT.innerText='';
                    for(z in arrJSon[y]){
                        teT.innerHTML+=`<option  value="">${arrJSon[y][z].name}</option>`;//在第二个select内添加与选中省份相同的id值的城市名
                    }
                }
            }
        }
    }
}

function gePot(gp,tet,tf,date,fn) {
    var nex=null;
    if(window.XMLHttpRequest){
        nex=new XMLHttpRequest();
    }
    else{
        nex=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if(gp=="post"){
        nex.open("post",tet,tf);
        nex.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
        nex.send(data);
    }
    else if(gp=="get"){
        nex.open("get",tet,tf);
        nex.send();
    }
    nex.onreadystatechange=function () {
        if(nex.readyState==4&&nex.status==200){
            fn(nex.responseText);
        }
    }
}


HTML:

<select name="province" class="text">
    <option value="0">选择省</option>
</select>
<select id="city" name="city">
    <option value="0">选择市</option>
</select>






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值