【问题标题】:Passing variables (server side / client side ) node js传递变量(服务器端/客户端)节点js
【发布时间】:2016-08-18 10:29:49
【问题描述】:

刚开始使用 node、express 和 mongodb (mongoose),这就是我想要做的:

  1. 通过表单将jade文件中的参数传回index.js ✔
  2. 在index.js中查询结果✔
  3. 然后将结果返回到jade并显示出来✖

search.jade

form(action='/searchByTitle', method='get')
    input(type='text' name ='docTitle' placeholder='Title')
    input(type="submit" value = 'submit')

index.js

...
var Document = require('../models/document');
...

router.get('/search', function(req, res){   
        res.render('search');
});

router.get('/searchByTitle', function(req, res){

    var title = req.param('docTitle');

    Document.find({ title: title }, function(err, doc) {
        if (err) throw err;
          console.log(doc);
        });         
}); 

console.log(doc)我得到一个json对象:

[ { _id: 57b4725b3cd1c8a028a6f686,
    title: 'title123',
    category: 'category123',
    author: 'Anne',
    date: Thu Aug 25 2016 02:00:00 GMT+0200 (Central European Daylight Time),
    version: 1,
    file: 'test.txt',
    __v: 0 } ]

如何将该对象传递回 search.jade 以便在页面上显示它?

我知道我可以做到res.render('search', {doc: doc});,但是当它被渲染时,页面已经显示出来了。我是否必须以某种方式更改路线?

【问题讨论】:

  • 你试过 res.json(doc) 吗?
  • 它可以工作,它会显示在浏览器中,但我的问题是如何在 search.jade 中的搜索表单旁边显示它..

标签: node.js mongodb express mongoose


【解决方案1】:

从 searchByTitle 再次渲染 search.jade。

router.get('/searchByTitle', function(req, res){

var title = req.param('docTitle');

Document.find({ title: title }, function(err, doc) {
    if (err) throw err;
      console.log(doc);
      res.locals.doc = doc;
      res.render('search');
    });         
}); 

然后使用 search.jade 中的文档。

form(action='/searchByTitle', method='get')
input(type='text' name ='docTitle' placeholder='Title')
input(type="submit" value = 'submit')
if(doc)
     //render the doc.

【讨论】:

  • 工作就像一个魅力! res.locals 是解决方案.. 谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-06-20
  • 1970-01-01
  • 2014-02-13
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 2022-09-28
相关资源
最近更新 更多