我对AJAX很陌生,不确定问题出在哪里。我的网页通过AJAX get请求获取帖子上的所有评论。问题是,只有在刷新页面后才能成功完成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)
})
在重新加载前,评论对象是空对象。
![blank object](https://istack.dev59.com/r2SRK.webp)
![enter image description here](https://istack.dev59.com/irCOp.webp)