javascript - 对 nodejs 服务器的 jquery ajax 请求仅适用于页面刷新

标签 javascript jquery node.js ajax

我对 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)

})

commets 对象在重新加载之前的样子 - 空白对象 blank object

重新加载后评论对象的样子enter image description here

当您导航到不同的帖子/不同的 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/

相关文章:

javascript - JQuery 选择器 : How to get a img id that have an one and only one attribute

jquery - 更改 CSS 以便图像填充 jQuery 选项卡

Javascript 获取错误的背景图像源

jquery - 速度表图形帮助/jQuery 和 CSS3

node.js - 使用 Node.js 插入数据

javascript - 导出 mongoose 数据库模块

javascript - 如何删除其中包含特定文本的div

javascript - 使用 Chrome 使用 Java 脚本打开 QTP (UFT)

javascript - 我应该使用什么正则表达式来匹配这个日期模式 : DAY. month.YEAR?

javascript - 用户连接时 socket.io 未注册