1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>省市区三级联动</title> 6 <style type="text/css"> 7 #showInfo{ 8 position: absolute; 9 width: 600px; 10 height: 500px; 11 overflow-y: scroll; 12 overflow-x: hidden; 13 background: lightgreen; 14 left: 50%; 15 margin-left: -300px; 16 } 17 #showInfo div{ 18 float:left; 19 margin-left: 30px; 20 margin-top: 30px; 21 width: 160px; 22 } 23 #showInfo div select{ 24 width: 160px; 25 } 26 </style> 27 <script type="text/javascript" src="./jquery-1.11.2.js"></script> 28 <script type="text/javascript"> 29 $(function() { 30 //获取列表数据的通用方法 31 function getList(code,flag,callback){ 32 $.ajax({ 33 url:'./data.php', 34 type:'get', 35 dataType:"jsonp", 36 data:{citycode:code,flag:flag}, 37 success:callback 38 }); 39 } 40 //获取地区信息的回调函数 41 var area = function(data){ 42 $.each(data,function(i,element){ 43 var op = $("<option></option>").attr("value",element.code).append(element.name); 44 $("#area").append(op); 45 }); 46 } 47 //获取市信息的回调函数 48 var city = function(data){ 49 $.each(data,function(i,element){ 50 var op = $("<option></option>").attr("value",element.code).append(element.name); 51 $("#city").append(op); 52 }); 53 //判断是否为直辖市 54 if(data.length == 1){ 55 var citycode = $("#city").children("option").eq(0).attr("value"); 56 getList(citycode,3,area); 57 } 58 59 } 60 //获得省份信息的回调函数 61 var province = function(data){ 62 $.each(data,function(i,element){ 63 var op = $("<option></option>").attr("value",element.code).append(element.name); 64 $("#province").append(op); 65 }); 66 //默认北京市 67 getList('110000',2,city); 68 getList('110100',3,area); 69 } 70 71 //发送请求获取省份信息 72 getList(0,1,province); 73 74 //给省份信息设置选择事件 75 $("#province").change(function() { 76 $("#city").children("option").remove(); 77 $("#area").children("option").remove(); 78 var pcode = $(this).val(); 79 getList(pcode,2,city); 80 }); 81 82 //给省份信息设置选择事件 83 $("#city").change(function() { 84 $("#area").children("option").remove(); 85 var citycode = $(this).val(); 86 getList(citycode,3,area); 87 }); 88 89 }); 90 </script> 91 </head> 92 <body> 93 <div id="showInfo"> 94 <div> 95 <select id="province"> 96 </select> 97 </div> 98 <div> 99 <select id="city"> 100 </select> 101 </div> 102 <div> 103 <select id="area"> 104 </select> 105 </div> 106 </div> 107 </body> 108 </html>