将mongoose查询中的变量发送到页面而不单击重新加载

时间:2017-11-11 18:30:29

标签: node.js express mongoose

我的网站上有链接。单击它时,它将调用一个执行mongoose查询的函数。 我想将该查询的结果发送到变量中的同一页面而不重新加载页面。我怎么做?现在它只是使用新的查询结果数据再次呈现页面。

// List comments for specified chapter id.
commentController.list = function (req, res) {
  var chapterId = req.params.chapterId;
  var query = { chapterId: chapterId };
  Chapter.find({ _id: chapterId }).then(function (chapter) {
    var chapter = chapter;
   Comment.find(query).then(function (data) {
  console.log(chapter);


    Chapter.find().then(function(chapters){
      return res.render({'chapterlinks', commentList: data, user: req.user, chapterq: chapter, chapters:chapters });

    })

});

}) };

1 个答案:

答案 0 :(得分:1)

您只需要通过 AJAX

从浏览器提出该请求

https://www.w3schools.com/xml/ajax_intro.asp

这将在您的客户端(浏览器)的代码中,而不是您的服务器的代码(nodejs)。

<强>更新

这是一个简单的示例,它使用 jQuery 来简化操作:

(1)创建一个执行和处理ajax请求的函数

function getChapterLinks(chapterId) {
    $.ajax({
      url: "/chapterLinks/"+chapterId,
    }).done(function(data) {
      //here you should do something with data
      console.log(data);
    });
}

(2)将该功能绑定到DOM元素的点击事件

$( "a#chapterLinks1" ).click(function() {
  getChapterLinks(1);
});

(3)确保DOM元素位于你的html

<a id="chapterLinks1">Get ChapterLinks 1</a>

现在,当点击此a#chapterLinks1元素时,它将使用 AJAX 从您的服务器获取/chaptersLink/1的响应,而无需重新加载页面。

的引用:

http://api.jquery.com/jquery.ajax/

http://api.jquery.com/jquery.click/