MySQL二级联动通常指的是在一个Web应用中,通过两个下拉菜单(或选择框)实现数据的级联选择。例如,在一个电商网站中,第一个下拉菜单选择商品类别,第二个下拉菜单则根据选择的类别显示相应的商品品牌。这种功能通常通过前端JavaScript与后端MySQL数据库交互实现。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MySQL二级联动示例</title>
</head>
<body>
<select id="category" onchange="loadBrands()">
<option value="">请选择类别</option>
<!-- 动态加载类别选项 -->
</select>
<select id="brand">
<option value="">请选择品牌</option>
<!-- 动态加载品牌选项 -->
</select>
<script>
function loadCategories() {
fetch('/api/categories')
.then(response => response.json())
.then(data => {
const categorySelect = document.getElementById('category');
data.forEach(category => {
const option = document.createElement('option');
option.value = category.id;
option.textContent = category.name;
categorySelect.appendChild(option);
});
});
}
function loadBrands() {
const categoryId = document.getElementById('category').value;
fetch(`/api/brands?categoryId=${categoryId}`)
.then(response => response.json())
.then(data => {
const brandSelect = document.getElementById('brand');
brandSelect.innerHTML = '<option value="">请选择品牌</option>';
data.forEach(brand => {
const option = document.createElement('option');
option.value = brand.id;
option.textContent = brand.name;
brandSelect.appendChild(option);
});
});
}
loadCategories();
</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/categories', (req, res) => {
const sql = 'SELECT * FROM categories';
db.query(sql, (err, result) => {
if (err) throw err;
res.json(result);
});
});
app.get('/api/brands', (req, res) => {
const categoryId = req.query.categoryId;
const sql = 'SELECT * FROM brands WHERE category_id = ?';
db.query(sql, [categoryId], (err, result) => {
if (err) throw err;
res.json(result);
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
通过以上步骤和示例代码,你可以实现一个基本的MySQL二级联动功能。根据具体需求,可以进一步优化和扩展。
领取专属 10元无门槛券
手把手带您无忧上云