在JavaScript中实现“只能点赞一次”的功能,通常涉及到前端与后端的交互。以下是相关的基础概念、优势、类型、应用场景以及解决方案:
// 假设有一个点赞按钮
const likeButton = document.getElementById('like-button');
let hasLiked = false;
likeButton.addEventListener('click', async () => {
if (hasLiked) {
alert('你已经点过赞了!');
return;
}
// 发送点赞请求到后端
try {
const response = await fetch('/api/like', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ postId: '123' }) // 假设postId是你要点赞的帖子ID
});
if (response.ok) {
hasLiked = true;
likeButton.disabled = true; // 禁用按钮
likeButton.innerText = '已点赞';
} else {
alert('点赞失败,请重试');
}
} catch (error) {
console.error('Error:', error);
alert('点赞失败,请重试');
}
});
const express = require('express');
const app = express();
app.use(express.json());
const likes = {}; // 存储点赞状态
app.post('/api/like', (req, res) => {
const { postId } = req.body;
if (!postId) {
return res.status(400).json({ message: '缺少postId' });
}
if (likes[postId]) {
return res.status(400).json({ message: '你已经点过赞了' });
}
likes[postId] = true;
res.status(200).json({ message: '点赞成功' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
hasLiked
变量来记录用户是否已经点赞。hasLiked
状态。likes
来存储每个帖子的点赞状态。通过前后端结合的方式,可以有效实现“只能点赞一次”的功能,提升用户体验和数据安全性。
领取专属 10元无门槛券
手把手带您无忧上云