要在HTML网页中添加景区收藏⭐️功能,并将收藏信息保存到MySQL数据库中,我们可以结合使用HTML、JavaScript和服务器端的技术(如Node.js)来实现。下面是一个基本的实现步骤:
🌱准备工作:
确保你已经安装了Node.js和MySQL,并创建了一个名为scenic_spots的数据库以及一个名为spots的表,包含id、name和location字段。
创建一个Node.js项目,并安装Express和MySQL模块。
在HTML中添加收藏按钮:
在HTML网页中添加一个按钮,用于收藏景区。例如:
(1) html代码区域:
<button οnclick="favoriteScenicSpot('1')">收藏景区1</button>
编写JavaScript函数处理收藏操作:
在JavaScript中编写一个函数,用于处理收藏操作,并通过AJAX将收藏信息发送给服务器。
(2) javascript代码区域:
function favoriteScenicSpot(id) {
// 发送POST请求到服务器,告知服务器收藏哪个景区
fetch('/favorite', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: id })
}).then(response => {
if (response.ok) {
alert('景区已成功收藏!');
} else {
alert('收藏失败,请重试!');
}
}).catch(error => {
console.error('收藏失败:', error);
alert('收藏失败,请重试!');
});
}
在Node.js中编写服务器端代码处理收藏请求:
在Node.js中编写路由处理器,用于接收客户端发送的收藏请求,并将收藏信息保存到MySQL数据库中。
(3) javascript代码区域:
const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3000;
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'scenic_spots'
});
app.use(express.json());
app.post('/favorite', (req, res) => {
const { id } = req.body;
connection.query('INSERT INTO spots (id) VALUES (?)', [id], (error, results, fields) => {
if (error) {
console.error('添加景区失败:', error);
res.status(500).send('添加景区失败');
return;
}
console.log('景区已成功收藏');
res.status(200).send('景区已成功收藏');
});
});
app.listen(port, () => {
console.log(`应用运行在 http://localhost:${port}`);
});