二级联动通常指的是在前端页面上,通过两个下拉菜单实现数据的级联选择。例如,选择省份后,城市列表会根据所选省份自动更新。这种功能通常需要后端配合,从数据库中查询相关数据并返回给前端。
-- 省份表
CREATE TABLE provinces (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL
);
-- 城市表
CREATE TABLE cities (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
province_id INT,
FOREIGN KEY (province_id) REFERENCES provinces(id)
);
from flask import Flask, jsonify, request
import mysql.connector
app = Flask(__name__)
def get_cities(province_id):
conn = mysql.connector.connect(user='user', password='password', host='host', database='database')
cursor = conn.cursor()
query = "SELECT id, name FROM cities WHERE province_id = %s"
cursor.execute(query, (province_id,))
cities = cursor.fetchall()
cursor.close()
conn.close()
return cities
@app.route('/api/cities', methods=['GET'])
def api_cities():
province_id = request.args.get('province_id')
cities = get_cities(province_id)
return jsonify(cities)
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>二级联动示例</title>
</head>
<body>
<select id="province">
<option value="">请选择省份</option>
<!-- 省份选项 -->
</select>
<select id="city">
<option value="">请选择城市</option>
<!-- 城市选项 -->
</select>
<script>
document.getElementById('province').addEventListener('change', function() {
var provinceId = this.value;
if (provinceId) {
fetch(`/api/cities?province_id=${provinceId}`)
.then(response => response.json())
.then(data => {
var citySelect = document.getElementById('city');
citySelect.innerHTML = '<option value="">请选择城市</option>';
data.forEach(city => {
var option = document.createElement('option');
option.value = city.id;
option.textContent = city.name;
citySelect.appendChild(option);
});
});
}
});
</script>
</body>
</html>
通过以上步骤和示例代码,可以实现一个基本的二级联动功能。根据具体需求,可以进一步优化和扩展。
领取专属 10元无门槛券
手把手带您无忧上云