从页面帖子中获取用户评论通常涉及到前端和后端的协同工作。以下是一个基本的流程和相关概念:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>获取用户评论</title>
</head>
<body>
<div id="comments"></div>
<textarea id="commentInput" placeholder="输入你的评论"></textarea>
<button onclick="submitComment()">提交评论</button>
<script>
async function fetchComments() {
const response = await fetch('/api/comments');
const comments = await response.json();
displayComments(comments);
}
function displayComments(comments) {
const commentsDiv = document.getElementById('comments');
commentsDiv.innerHTML = '';
comments.forEach(comment => {
const p = document.createElement('p');
p.textContent = comment.text;
commentsDiv.appendChild(p);
});
}
async function submitComment() {
const commentInput = document.getElementById('commentInput');
const commentText = commentInput.value;
await fetch('/api/comments', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ text: commentText })
});
commentInput.value = '';
fetchComments();
}
// 初始加载评论
fetchComments();
</script>
</body>
</html>
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
let comments = [];
app.get('/api/comments', (req, res) => {
res.json(comments);
});
app.post('/api/comments', (req, res) => {
const newComment = { text: req.body.text };
comments.push(newComment);
res.status(201).send();
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
通过上述步骤和代码示例,你可以实现一个基本的用户评论系统。根据具体需求,还可以进一步优化和扩展功能。
领取专属 10元无门槛券
手把手带您无忧上云