ajax三级联动操作

Original 2019-04-30 16:39:15 304
abstract:<!DOCTYPE html><html><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta http-equ

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<meta http-equiv="X-UA-Compatible" content="ie=edge" />

<script type="text/javascript" src="jquery-3.2.1.min.js"></script>

<title>Document</title>

</head>

<body>


省:<select name="provice" id="provice"></select><br />

市:<select name="city" id="city"></select><br />

区:<select name="sarea" id="sarea"></select><br />

详细:<input type="text" name="address"/><br />



<script type="text/javascript">

$(function(){

//自动加载省份列表

$.getJSON('test.json',function(data){

var obj=data['items'];

var option ='<option value="0">请选择省份</option>';

for (var i=0;i<obj.length;i++) {

option +='<option value="'+obj[i].areaId+'">'+obj[i].province+'</option>';

}

$('#provice').html(option);

});

})



//change事件 选择省份   change事件不能放在就绪函数里

$('#provice').on('change',function(){

var provice=$("#provice").val();  

if(provice==0){

$("#city").html('');

}else{

$.ajax({

type:"GET",

url:"test.json",

dataType:'json',

data:{provice:'provice'},

success:function(data){

var obj=data['items'];

var option ='<option value="0">请选择城市</option>';

for (var i=0;i<obj.length;i++) {

if(obj[i].areaId==provice){

for (var j=0;j<obj[i].cityList.length;j++) {

var obj_city=obj[i].cityList;

 

option +='<option value="'+obj_city[j].areaId+'">'+obj_city[j].city+'</option>';

}

}

}

$('#city').html(option);

}

});

}

})




//change事件 选择城市   change事件不能放在就绪函数里

$('#city').on('change',function(){

var provice=$("#provice").val();  

var city=$("#city").val();  

if(city==0){

$("sarea").html('');

}else{

$.ajax({

type:"GET",

url:"test.json",

dataType:'json',

data:{city:'city'},

success:function(data){

var obj=data['items'];

var option ='<option value="0">请选择区</option>';

  for (var i=0;i<obj.length;i++) {

   var obj_city=obj[i].cityList;

    for (var j=0;j<obj_city.length;j++) {

       if(city==obj_city[j].areaId){

        var areaList=obj_city[j]['areaList'];

        console.log(areaList)

        for (var m=0;m<areaList.length;m++) {

option +='<option value="'+areaList[m].areaId+'">'+areaList[m].area+'</option>';

        }

$('#sarea').html(option);

       }else{

        $('#sarea').html();

       }

    }

 

}

  

}

});

}

})

</script>


</body>

</html>

1.png2.png3.png5.png



Correcting teacher:查无此人Correction time:2019-05-05 09:54:35
Teacher's summary:完成的不错。下次把代码缩进,整齐些。继续加油。

Release Notes

Popular Entries