【html+js】怎么在html旅游网页的风景区添加景区收藏功能,并收藏到mysql数据库里面
    		       		warning:
    		            这篇文章距离上次修改已过446天,其中的内容可能已经有所变动。
    		        
        		                
                在HTML+JS中实现景区收藏功能并将数据保存到MySQL数据库需要以下步骤:
- 创建一个前端页面,包含景区信息和一个收藏按钮。
 - 使用JavaScript发起AJAX请求到后端API,将用户的收藏操作记录下来。
 - 后端API接收请求,进行身份验证和权限检查,然后将收藏信息保存到MySQL数据库中。
 
前端代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>景区收藏</title>
    <script>
        function addFavorite(scenicSpotId) {
            // 发起AJAX请求到后端API
            fetch('/api/add-favorite', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    scenicSpotId: scenicSpotId
                })
            }).then(response => {
                if (response.ok) {
                    alert('收藏成功!');
                } else {
                    alert('收藏失败,请重试!');
                }
            });
        }
    </script>
</head>
<body>
    <h1>五四广场旅游景区</h1>
    <button onclick="addFavorite(54gq)">收藏景区</button>
</body>
</html>后端API代码示例(使用Node.js和Express):
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
 
const app = express();
app.use(bodyParser.json());
 
// MySQL连接配置
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'username',
    password: 'password',
    database: 'travel_database'
});
 
// 收藏景区的API
app.post('/api/add-favorite', (req, res) => {
    const scenicSpotId = req.body.scenicSpotId;
    const userId = 'user-identifier'; // 用户标识,应从认证系统获取
 
    // 插入收藏到MySQL
    connection.query('INSERT INTO favorites (userId, scenicSpotId) VALUES (?, ?)', [userId, scenicSpotId], (error, results, fields) => {
        if (error) {
            res.status(500).send('数据库错误');
            return;
        }
        res.status(200).send('收藏成功');
    });
});
 
app.listen(3000, () => {
    console.log('API服务器运行在 http://localhost:3000');
});确保你有一个MySQL数据库,其中有一个名为favorites的表,包含userId和scenicSpotId字段。
注意:这只是一个简化示例,实际应用中需要考虑用户认证、权限管理、错误处理等多个方面。
评论已关闭