ez-site/includes/love.php

83 lines
3.2 KiB
PHP
Raw Normal View History

2024-10-19 21:33:47 +08:00
<div class="container">
<h1>表白墙</h1>
<?php if (isset($_SESSION['user_id'])): ?>
<form method="POST" id="loveForm" action="/?api=submit_love">
<div class="form-group">
<textarea name="content" placeholder="写点什么呢?" required></textarea>
</div>
<button type="submit">发表</button>
</form>
<?php else: ?>
<p><a href="/?page=account">登录</a>后发表内容。</p>
<?php endif; ?>
<h2>表白内容</h2>
<div id="loveWall">
<?php
$stmt = $pdo->prepare("SELECT love_wall.id, love_wall.content, users.username FROM love_wall JOIN users ON love_wall.user_id = users.id ORDER BY love_wall.created_at DESC");
$stmt->execute();
while ($row = $stmt->fetch()) {
echo "<div class='love-message'><strong>" . htmlspecialchars($row['username']) . ":</strong> " . htmlspecialchars($row['content']) . "</div>";
echo "<div class='comment-section' id='comments-{$row['id']}'>";
// 加载评论
$commentStmt = $pdo->prepare("SELECT comments.content, users.username FROM comments JOIN users ON comments.user_id = users.id WHERE love_wall_id = ? ORDER BY comments.created_at DESC");
$commentStmt->execute([$row['id']]);
while ($comment = $commentStmt->fetch()) {
echo "<div class='comment'><strong>" . htmlspecialchars($comment['username']) . ":</strong> " . htmlspecialchars($comment['content']) . "</div>";
}
echo "</div>";
if (isset($_SESSION['user_id'])) {
echo "<form method='POST' class='commentForm' data-love-wall-id='{$row['id']}'>";
echo "<textarea name='commentContent' placeholder='发表评论...' required></textarea>";
echo "<button type='submit'>评论</button>";
echo "</form>";
}
echo "<hr>";
}
?>
</div>
</div>
<script>
document.querySelectorAll('.commentForm').forEach(form => {
form.addEventListener('submit', function(event) {
event.preventDefault();
var formData = new FormData(this);
formData.append('love_wall_id', this.dataset.loveWallId);
fetch('/?api=submit_comment', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
this.querySelector('textarea[name="commentContent"]').value = '';
loadComments(this.dataset.loveWallId);
alert('评论成功!');
})
.catch(error => {
console.error('Error:', error);
alert('评论失败,请稍后再试!');
});
});
});
function loadComments(loveWallId) {
fetch('/?api=load_comments&love_wall_id=' + loveWallId)
.then(response => response.text())
.then(data => {
document.getElementById('comments-' + loveWallId).innerHTML = data;
})
.catch(error => {
console.error('Error:', error);
alert('加载评论失败,请稍后再试!');
});
}
</script>
</body>
</html>