以下是使用Node.js, Express, jQuery, Ajax, MySQL, 以及 Bootstrap Select 创建省-市-县三级联动下拉菜单的基本示例代码。
首先,确保你已经安装了Node.js和MySQL。
- 安装Express和MySQL连接器:
npm install express mysql
- 创建一个简单的Express服务器,并设置路由以处理Ajax请求:
const express = require('express');
const mysql = require('mysql');
const app = express();
// 连接MySQL数据库
const connection = mysql.createConnection({
host : 'localhost',
user : 'your_username',
password : 'your_password',
database : 'your_database'
});
connection.connect();
// 省市县的Ajax接口
app.get('/api/provinces', (req, res) => {
connection.query('SELECT * FROM provinces', (error, results) => {
if (error) throw error;
res.json(results);
});
});
app.get('/api/cities/:provinceId', (req, res) => {
const provinceId = req.params.provinceId;
connection.query('SELECT * FROM cities WHERE provinceId = ?', [provinceId], (error, results) => {
if (error) throw error;
res.json(results);
});
});
app.get('/api/districts/:cityId', (req, res) => {
const cityId = req.params.cityId;
connection.query('SELECT * FROM districts WHERE cityId = ?', [cityId], (error, results) => {
if (error) throw error;
res.json(results);
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
- 创建数据库表:
CREATE TABLE provinces (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
CREATE TABLE cities (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
provinceId INT,
FOREIGN KEY (provinceId) REFERENCES provinces(id)
);
CREATE TABLE districts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
cityId INT,
FOREIGN KEY (cityId) REFERENCES cities(id)
);
- 创建HTML页面,并使用jQuery和Ajax加载省市县数据,并使用Bootstrap Select插件显示下拉菜单:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>三级联动下拉菜单</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstra