案例:从数据库获取数据实现省市区三级联动,如下图所示
思路:网页初始化时,先获取所有的省份,通过被选中的省份id去获取所有城市,在通过被选中的城市id去加载所有的区县,
当所选的省市的id发生改变时,触发change事件,去加载相应的省市区。
代码如下:
html:
js:
loadProv();//初始化
//当select标签内容发生改变是触发事件
$(".prov").change(function() {
loadCity();
});
$(".city").change(function() {
loadCounty();
});
//加载省份
function loadProv() {
$.ajax({
type: "post",
url: "http://loaclhost/interface/pc_region/get_pro_list.do",
dataType: "json",
async: false, //同步
success: function(result) {
var provlist = result.result_info;
//console.log(citylist);
var str = ''
for(var i = 0; i < provlist.length; i++) {
str += ''
}
$(".prov").html(str);
loadCity(); //加载城市
},
error: function() {
console.log("获取省份失败");
}
});
}
function loadCity() {
var prov_id = $(".prov").find("option:selected").val();
$.ajax({
type: "post",
url: "http://loaclhost/interface/pc_region/get_city_list.do",
data: {
prov_id: prov_id
},
dataType: "json",
async: true,
success: function(result) {
var citylist = result.result_info;
//console.log(citylist);
var str = ''
for(var i = 0; i < citylist.length; i++) {
str += ''
}
$(".city").html(str);
loadCounty();
},
error: function() {
console.log("获取城市失败");
}
});
}
//加载各区县
function loadCounty() {
var prov_id = $(".prov").find("option:selected").val();
var city_id = $(".city").find("option:selected").val();
$.ajax({
type: "post",
url: "http://loaclhost/interface/pc_region/get_county_list.do",
async: true,
data: {
prov_id: prov_id,
city_id: city_id
},
dataType: "json",
async: true,
success: function(result) {
var countylist = result.result_info;
//console.log(citylist);
var str = ''
for(var i = 0; i < countylist.length; i++) {
str += ''
}
$(".county").html(str);
},
error: function() {
console.log("获取区县失败");
}
});
}
后台:
1、获取所有省份:http://loaclhost/interface/pc_region/get_pro_list.do
2、获取所有城市:http://loaclhost/interface/pc_region/get_city_list.do(根据省份id)
3、获取所有区县:http://loaclhost/interface/pc_region/get_county_list.do(根据省份id和城市id)
ps:设置默认选中的省市区
$("#prov").find("option[value='"+preenter.province_id+"']").attr("selected",true); //设置被选中
$("#prov").find("option[value='"+preenter.province_id+"']").trigger("change"); //设置触发change函数
$("#city").find("option[value='"+preenter.city_id+"']").attr("selected",true);
$("#city").find("option[value='"+preenter.city_id+"']").trigger("change");
$("#county").find("option[value='"+preenter.county_id+"']").attr("selected",true);