HTML/Html-practice/Ajax/基于jQuery的AJAX实现三级联动菜单/js/index.js

69 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-05-01 21:33:04 +08:00
function getData(){
$.ajax({
url : './json/third-level-address.json',
type : 'get',
async: false,
success : function(data) {
if(data=="error"){
alert("系统错误");
return;
}
dataJson=data;
}
});
return dataJson;
}
2023-05-01 21:47:33 +08:00
function getCountry(){
2023-05-01 21:33:04 +08:00
var data = getData();
2023-05-01 20:26:29 +08:00
var country = new Array();
var children = new Array();
var countryCode=new Array();
$.each(data,function(i,tmp){
countryCode.push(tmp.code);
country.push(tmp.name);
children.push(tmp.children);
});
2023-05-01 21:33:04 +08:00
// for(var i in data){
2023-05-01 21:47:33 +08:00
// console.log(data[i].children[0].children.length);
2023-05-01 21:33:04 +08:00
// }
2023-05-01 20:26:29 +08:00
var options = "<option value='0'>--请选择--</option>";
for(var i in data){
2023-05-01 21:33:04 +08:00
options += "<option value='" + data[i].code + "' selected>" + dataJson[i].name+"</option>";
2023-05-01 20:26:29 +08:00
$("#province").html(options);
// console.log(data[i].code);
}
}
2023-05-01 21:33:04 +08:00
function getCity(countryCode){
var data = getData();
$('#city').empty();
var options = "<option value='0'>--请选择--</option>";
for(var i in data){
2023-05-01 21:47:33 +08:00
for(let j=0;j<data[i].children.length;j++){
if(countryCode && countryCode == data[i].code){
options += "<option value='" + data[i].children[j].code + "' selected>" + data[i].children[j].name+"</option>";
2023-05-01 21:33:04 +08:00
}
2023-05-01 21:47:33 +08:00
}
2023-05-01 21:33:04 +08:00
$("#city").html(options);
}
}
function getArea(cityCode){
var data = getData();
var options = "<option value='0'>--请选择--</option>";
for(var i in data){
2023-05-01 21:47:33 +08:00
for(let j=0;j<data[i].children.length;j++){
for(let k=0;k<data[i].children[j].children.length;k++){
if(cityCode && cityCode == data[i].children[j].code){
options += "<option value='" + data[i].children[j].children[k].code + "' selected>" + data[i].children[j].children[k].name+"</option>";
}
}
}
2023-05-01 21:33:04 +08:00
$("#area").html(options);
}
2023-05-01 20:26:29 +08:00
}