本文将阐述如何使用jquery框架解析复杂json数据(把数据中属于直辖市或特别行政区进行处理,格式化数据),并渲染到页面
案例效果图如下:
所有地址信息文件:http://59.110.140.61/file/city.json请自行下载。
格式化前的数据为(需要将直辖市和特别行政区分离出来):
格式化后的数据为:
具体实现代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
</style>
<body>
<select name="" id="province">
</select>
<select name="" id="city">
<option value="">请选择</option>
</select>
<select name="" id="town">
<option value="">请选择</option>
</select>
</body>
<script src="./jquery.min.js"></script>
<script>
$.ajax({
url: './city.json',
success: res => {
var str = '<option value="">请选择</option>';
res = formatData(res.list);
res.forEach(({city_id,name}) => {
str += `<option value="${city_id}" class='active'>${name}</option>`;
})
$('#province').append(str);
$('#province').change(function(){
$('#city').empty();
$('#city').append('<option value="">请选择</option>');
$('#town').empty();
$('#town').append('<option value="">请选择</option>');
if(!$('#province').val()){
return;
}
var city_id = $(this).val();
selectCity(res,city_id);
})
}
})
function selectCity(res,city_id){
var cityList = res.filter(item=>{
if(item.city_id == city_id){
return item;
}
})[0].list;
var str = '<option value="">请选择</option>';
cityList.forEach(({city_id,name})=>{
str += `<option value="${city_id}">${name}</option>`;
})
$('#city').empty();
$('#city').append(str);
$('#city').change(function(){
var city_id = $(this).val();
selectX(cityList,city_id);
})
}
function selectX(cityList,city_id){
var xListn = cityList.filter(item=>{
if(item.city_id == city_id){
return item;
}
})[0].list;
console.log(xListn);
var str = '<option value="">请选择</option>';
xListn.forEach(({city_id,name})=>{
str += `<option value="${city_id}">${name}</option>`;
})
$('#town').empty();
$('#town').append(str);
}
function formatData(res) {
var a = [];
for (var i = 0; i < 4; i++) {
a.push(res.shift());
}
var b = [];
var arr = res.filter(item => {
if (item.name == '香港' || item.name == '澳门') {
b.push(item);
} else {
return item;
}
})
arr.unshift({
name: '直辖市',
city_id: 'CH99',
list: a
}, {
name: '特别行政区',
city_id: 'CH98',
list: b
});
return arr;
}
</script>
</html>