Java与MySQL的三级联动通常指的是在Java Web应用程序中,通过MySQL数据库实现三级联动的下拉选择框(例如:省-市-区)。这种功能允许用户在选择上一级选项时,动态加载下一级的选项。
三级联动主要分为以下几种类型:
三级联动广泛应用于各种需要层级关系的表单选择,如地址选择、分类选择等。
以下是一个简单的Java与MySQL实现三级联动的示例:
假设有三个表:province
(省)、city
(市)、district
(区)。
CREATE TABLE province (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE city (
id INT PRIMARY KEY,
name VARCHAR(50),
province_id INT,
FOREIGN KEY (province_id) REFERENCES province(id)
);
CREATE TABLE district (
id INT PRIMARY KEY,
name VARCHAR(50),
city_id INT,
FOREIGN KEY (city_id) REFERENCES city(id)
);
@RestController
@RequestMapping("/api")
public class LocationController {
@Autowired
private LocationService locationService;
@GetMapping("/provinces")
public List<Province> getProvinces() {
return locationService.getProvinces();
}
@GetMapping("/cities")
public List<City> getCities(@RequestParam int provinceId) {
return locationService.getCities(provinceId);
}
@GetMapping("/districts")
public List<District> getDistricts(@RequestParam int cityId) {
return locationService.getDistricts(cityId);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>三级联动示例</title>
</head>
<body>
<select id="province" onchange="loadCities()">
<option value="">请选择省</option>
</select>
<select id="city" onchange="loadDistricts()">
<option value="">请选择市</option>
</select>
<select id="district">
<option value="">请选择区</option>
</select>
<script>
async function loadProvinces() {
const response = await fetch('/api/provinces');
const provinces = await response.json();
const provinceSelect = document.getElementById('province');
provinces.forEach(province => {
const option = document.createElement('option');
option.value = province.id;
option.textContent = province.name;
provinceSelect.appendChild(option);
});
}
async function loadCities() {
const provinceId = document.getElementById('province').value;
const response = await fetch(`/api/cities?provinceId=${provinceId}`);
const cities = await response.json();
const citySelect = document.getElementById('city');
citySelect.innerHTML = '<option value="">请选择市</option>';
cities.forEach(city => {
const option = document.createElement('option');
option.value = city.id;
option.textContent = city.name;
citySelect.appendChild(option);
});
}
async function loadDistricts() {
const cityId = document.getElementById('city').value;
const response = await fetch(`/api/districts?cityId=${cityId}`);
const districts = await response.json();
const districtSelect = document.getElementById('district');
districtSelect.innerHTML = '<option value="">请选择区</option>';
districts.forEach(district => {
const option = document.createElement('option');
option.value = district.id;
option.textContent = district.name;
districtSelect.appendChild(option);
});
}
loadProvinces();
</script>
</body>
</html>
希望以上信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云