我对 AJAX 很陌生,我不确定自己做错了什么。我有一个网页,它使用 AJAX 获取请求获取帖子的所有评论。问题是 AJAX 请求只有在网页刷新后才会成功。我禁用了缓存以查看是否可以解决问题,但事实并非如此。
例如,当我从帖子 A 刷新页面后获取第一条评论,然后转到网站上的帖子 B,帖子 A 的评论显示为帖子 B 的评论,然后当我刷新页面时帖子 B 的评论成功替换为帖子 B 的评论。
我正在使用 jQuery 发出请求:
$.ajax({
type: "GET",
url: someURL,
success: (comments) => {
console.log(comments);
comments.questions.forEach(questionComment => {
$('.questionComments').append(
`<div class="comment">
<p>${questionComment.content}</p>
</div>
`
)
});
comments.answers.forEach(answer => {
answer.forEach(answerComment => {
$(`.answer#${answerComment.forId} .answerComments`).append(
`<div class="comment">
<p>${answerComment.content}</p>
</div>
`
)
})
})
},
cache: false
})
服务器端:(express.js、 Mongoose )
let allComments = {}
app.get('/questions/:questionID/getComments', (req, res) => {
if (err) return console.error(err)
Comment.find({ forQuestion: true, forId: req.params.questionID }, (err, questionComments) => {
allComments['questions'] = questionComments
})
Answer.find({ questionId: req.params.questionID }, (err, answers) => {
if (err) return console.error(err);
allAnswerComments = []
answers.forEach(answer => {
Comment.find({ forAnswer: true, forId: answer._id }, (err, comments) => {
allAnswerComments.push(comments)
})
});
allComments['answers'] = allAnswerComments
})
res.send(allComments)
})
当您导航到不同的帖子/不同的 URL 时,来自上一个帖子/URL 的对象是新帖子的初始对象,然后当您重新加载页面时,将获取正确的对象。
最佳答案
根据您的描述,AJAX 请求在执行时有效,但问题是它只在页面加载时执行一次。让我们为此编写一个函数:
function sendAJAX() {
$.ajax({
type: "GET",
url: someURL,
success: (comments) => {
console.log(comments);
comments.questions.forEach(questionComment => {
$('.questionComments').append(
`<div class="comment">
<p>${questionComment.content}</p>
</div>
`
)
});
comments.answers.forEach(answer => {
answer.forEach(answerComment => {
$(`.answer#${answerComment.forId} .answerComments`).append(
`<div class="comment">
<p>${answerComment.content}</p>
</div>
`
)
})
})
},
cache: false
})
}
并确保定期调用它:
sendAJAX();
seInterval(sendAJAX, 10000);
这仍然是不正确的,因为它会每十秒添加一次所有评论。为了改进这一点,您可以添加一个值来表示上次请求的时刻,并在服务器端仅加载在该时刻和当前请求之间创建的评论。
关于javascript - 对 nodejs 服务器的 jquery ajax 请求仅适用于页面刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64033003/