Nodejs中ajax如何传送id到客户端
Nodejs中ajax如何传送id到客户端
一篇博文,可以评论,任何人都能访问这篇博文,用ajax提交评论,那么提交数据中肯定得有这篇博文的id,服务端大家都是用什么方法把id传到客户端,让ajax能够提取id,上传评论的。
不懂在问什么…
不就是个json对象… 然后解析 ,返回 ,回调json 对象…
id 可以埋在网页的一个 hidden field 里。
最初下发给客户端的是html啊
你们都是这样弄的?
id 是你自己创建的话就用hidden。。。db 自动生成的就callback ///// 自己创建用 hidden 挺好的
要在Node.js中使用AJAX传递博文ID到客户端,通常的做法是将博文ID作为参数附加在URL中,或者通过POST请求的body传递。然后客户端可以通过JavaScript获取这个ID,并将其作为数据的一部分发送给服务器。
示例
后端(Node.js)
首先,我们假设有一个简单的Express应用来处理博文和评论的请求:
const express = require('express');
const app = express();
app.use(express.json());
// 模拟的数据库
let posts = [
{ id: 1, title: 'Post Title 1', comments: [] },
{ id: 2, title: 'Post Title 2', comments: [] }
];
app.get('/api/post/:postId', (req, res) => {
const postId = req.params.postId;
const post = posts.find(p => p.id == postId);
if (!post) return res.status(404).send('Post not found.');
res.send(post);
});
app.post('/api/post/:postId/comment', (req, res) => {
const postId = req.params.postId;
const comment = req.body.comment;
const post = posts.find(p => p.id == postId);
if (!post) return res.status(404).send('Post not found.');
post.comments.push(comment);
res.send(post.comments);
});
app.listen(3000, () => console.log('Server running on port 3000'));
前端(JavaScript + AJAX)
然后,在前端,你可以使用jQuery或原生JavaScript来发起AJAX请求:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button onclick="addComment()">Add Comment</button>
<script>
function addComment() {
const postId = 1; // 从URL或其他地方获取
const comment = prompt("Enter your comment");
$.ajax({
url: `/api/post/${postId}/comment`,
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ comment: comment }),
success: function(response) {
alert('Comment added successfully!');
console.log(response);
},
error: function(error) {
console.error(error);
}
});
}
</script>
</body>
</html>
在这个例子中,我们通过URL路径参数/api/post/:postId
传递了博文的ID,并在JavaScript中直接使用了一个固定的值postId = 1
来模拟这个过程。实际项目中,你可能需要从页面URL或其他动态来源获取这个ID。
这样,当用户点击按钮时,会弹出一个提示框让用户输入评论内容,然后使用AJAX向服务器发送这个评论及对应的博文ID。服务器接收到请求后,会根据传入的ID找到相应的博文,并更新其评论列表。