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 onclick='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>






猜你喜欢

转载自blog.csdn.net/weixin_42413651/article/details/80976551