1 PHP后台接口
<?php
/*
省市县后台数据接口
接口调用规则:
1、参数一:flag,用来区分请求的是省市县中间的那种数据(1:省,2:市;3:县)
2、参数二:选择省的时候传递pId,选择市的时候传递cId
http://localhost/select.php?flag=1&pId=23
http://localhost/select.php?flag=1&cd=2345
*/
// include('./selectdata.php');
// 引入数据文件
require('./selectdata.php');
// 省市县数据来自selectdata.php文件
$province = $provinceJson;
$city = $cityJson;
$county = $countyJson;
$flag = $_GET['flag'];
// 省级数据
if($flag == 1){
echo json_encode($province);
// 市级数据
}else if($flag == 2){
$pId = $_GET['pId'];
$cityData = array();
foreach ($city as $value) {
if($value->id == $pId){
// 直辖市
array_push($cityData,$value);
break;
}else if($value->parent == $pId){
// 非直辖市
array_push($cityData,$value);
}
}
echo json_encode($cityData);
// 县级数据
}else if($flag == 3){
$cId = $_GET['cId'];
$countyData = array();
foreach ($county as $value) {
if($value->parent == $cId){
array_push($countyData,$value);
}
}
echo json_encode($countyData);
}
?>
其中selectdata.php文件内容节选如下,主要是省市县各种信息。
<?php
$provinceJson = json_decode('[{"id":"2","province":"\u5317\u4eac\u5e02","parent":"1"},{"id":"19","province":"\u5929\u6d25\u5e02","parent":"1"}]');
$cityJson = json_decode('[{"id":"2","city":"\u5317\u4eac\u5e02","parent":"1"},{"id":"19","city":"\u5929\u6d25\u5e02","parent":"1"}]');
$countyJson = json_decode('[{"id":"3","county":"\u4e1c\u57ce\u533a","parent":"2"},{"id":"4","county":"\u897f\u57ce\u533a","parent":"2"}]');
?>
2 前端调用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>省市县三级联动</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./jquery.js"></script>
<style>
.container{
background-color: lightgray;
width: 500px;
height: 200px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<label>省:</label>
<select id="province"><option>
请选择省份
</option></select>
<label>市:</label>
<select id="city"><option>
请选择市
</option></select>
<label>县:</label>
<select id="county"><option>
请选择县
</option></select>
</div>
<script>
//公用方法
function query(obj,callback){
$.ajax({
type:'get',
url:'http://localhost:8080/summary/select.php',
data:obj,
dataType:'json',
success:function(data){
callback(data);
}
});
}
query(
{ flag:1},
function(data){
var options='';
$.each(data,function(i,e){
options+='<option value="'+e.id+'">'+e.province+'</option>';
});
$("#province").append(options);
});
$("#province").change(function(){
query({flag:2,pId:$(this).val()},function(data){
var options='';
$("#city option:gt(0)").remove();
$.each(data,function(i,e){
options+='<option value="'+e.id+'">'+e.city+'</option>';
});
$("#city").append(options);
});
});
$("#city").change(function(){
query({flag:3,cId:$(this).val()},function(data){
var options='';
$("#county option:gt(0)").remove();
$.each(data,function(i,e){
options+='<option value="'+e.id+'">'+e.county+'</option>';
});
$("#county").append(options);
});
});
</script>
</body>
</html>