传递变量(服务器端/客户端)节点JS
问题描述:
刚刚开始接触节点,快递和MongoDB(猫鼬),这就是我想要做的事:传递变量(服务器端/客户端)节点JS
- 得到玉文件参数返回索引通过形式的.js✔
- 查询结果中index.js✔
- 然后将结果返回到玉并显示它✖
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});
,但是当它被渲染时,页面已经被显示了。我是否必须以某种方式改变路线?
答
从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中的doc。
form(action='/searchByTitle', method='get')
input(type='text' name ='docTitle' placeholder='Title')
input(type="submit" value = 'submit')
if(doc)
//render the doc.
+0
工作就像一个魅力! res.locals是解决方案..谢谢! – bobby
你试过了res.json(doc)吗? – CamiloR
它的工作原理,它显示在浏览器中,但我的问题是如何显示它在search.jade搜索表单旁边。 – bobby