问题描述
我对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,猫鼬)
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 },answers) => {
if (err) return console.error(err);
allAnswerComments = []
answers.forEach(answer => {
Comment.find({ forAnswer: true,forId: answer._id },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);
这仍然是不正确的,因为它将每十秒钟添加所有评论。为了改善这一点,您可以添加一个代表最后一个请求时刻的值,并在服务器端仅加载在该时刻与当前请求之间创建的注释。
,能否请您描述一下在get参数上的工作方式,如何设置它。其中是否包含任何cookie?告诉get注释绝对可以帮助我们解决问题,而不用用open Script编写ajax,sendAjax()函数将是一个好主意。 另一方面,我永远不会建议您使用seInterval(sendAJAX,10000);而是安装服务工作者,并在添加新评论时从您的API中将其打回。然后,它应该仅获取最后一个并将其放入您的评论部分。
,根据您的描述,似乎主要问题是帖子A的评论出现在帖子B的评论中。
现在,所提供的数据最少,通过查看代码和代码,我假设您在从帖子A切换到帖子B时没有以编程方式刷新页面。
因此,问题的根本原因是附加。您正在将数据附加到您的div上。因此,在您的foreach循环之前,请先使用
清除html
$('.questionComments').html("")
对于答案,请按以下内容替换
comments.answers.forEach(answer => {
let first = true;
answer.forEach(answerComment => {
if(first) {
$(`.answer#${answerComment.forId} .answerComments`).html("")
first = false;
}
$(`.answer#${answerComment.forId} .answerComments`).append(
`<div class="comment">
<p>${answerComment.content}</p>
</div>
`
)
})
})
上面的代码片段只是为了说明您必须确定添加第一个注释的时间,然后将其重置。
我还没有测试代码段,但我希望您能了解代码中有什么问题。