点赞功能是一种常见的用户交互功能,允许用户对某个内容(如文章、评论、图片等)表示喜欢或支持。在Web应用中,点赞功能通常通过前端和后端的协同工作来实现。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点赞功能示例</title>
</head>
<body>
<div id="like-button">点赞</div>
<span id="like-count">0</span>
<script>
document.getElementById('like-button').addEventListener('click', function() {
fetch('/api/like', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ contentId: '123' })
})
.then(response => response.json())
.then(data => {
document.getElementById('like-count').innerText = data.likeCount;
});
});
</script>
</body>
</html><?php
header('Content-Type: application/json');
$contentId = $_POST['contentId'] ?? '';
// 假设数据库连接
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// 更新点赞数
$stmt = $db->prepare("UPDATE contents SET like_count = like_count + 1 WHERE id = ?");
$stmt->execute([$contentId]);
// 获取更新后的点赞数
$stmt = $db->prepare("SELECT like_count FROM contents WHERE id = ?");
$stmt->execute([$contentId]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode(['likeCount' => $result['like_count'] ?? 0]);
?>希望以上信息对你有所帮助!
没有搜到相关的文章