MySQL三级联动下拉菜单是一种常见的网页交互功能,通常用于表单中。它允许用户通过选择上一级的选项来动态加载下一级的选项。例如,在一个地区选择表单中,用户可以选择国家,然后根据所选国家动态加载省份,再根据所选省份动态加载城市。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MySQL三级联动下拉菜单</title>
</head>
<body>
<select id="country" onchange="loadProvinces()">
<option value="">请选择国家</option>
<!-- 动态加载国家选项 -->
</select>
<select id="province" onchange="loadCities()" disabled>
<option value="">请选择省份</option>
<!-- 动态加载省份选项 -->
</select>
<select id="city" disabled>
<option value="">请选择城市</option>
<!-- 动态加载城市选项 -->
</select>
<script>
async function loadProvinces() {
const countryId = document.getElementById('country').value;
const response = await fetch(`/api/provinces?countryId=${countryId}`);
const provinces = await response.json();
updateSelect('province', provinces);
}
async function loadCities() {
const provinceId = document.getElementById('province').value;
const response = await fetch(`/api/cities?provinceId=${provinceId}`);
const cities = await response.json();
updateSelect('city', cities);
}
function updateSelect(selectId, options) {
const select = document.getElementById(selectId);
select.innerHTML = '<option value="">请选择</option>';
options.forEach(option => {
const optionElement = document.createElement('option');
optionElement.value = option.id;
optionElement.textContent = option.name;
select.appendChild(optionElement);
});
select.disabled = false;
}
</script>
</body>
</html>
const express = require('express');
const mysql = require('mysql');
const app = express();
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test'
});
db.connect(err => {
if (err) throw err;
console.log('Connected to MySQL database');
});
app.get('/api/provinces', (req, res) => {
const countryId = req.query.countryId;
const query = 'SELECT * FROM provinces WHERE country_id = ?';
db.query(query, [countryId], (err, results) => {
if (err) throw err;
res.json(results);
});
});
app.get('/api/cities', (req, res) => {
const provinceId = req.query.provinceId;
const query = 'SELECT * FROM cities WHERE province_id = ?';
db.query(query, [provinceId], (err, results) => {
if (err) throw err;
res.json(results);
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
通过以上内容,你应该对MySQL三级联动下拉菜单有了全面的了解,并且知道如何实现和解决常见问题。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云