我以这种方式将mangoDB中的JSON对象发送到html页面:
router.get('/index', function (req, res, next) {
GenoverseInstance.find({name: req.query.name}, function (err, instance) {
if (err) {
res.send(err);
throw err;
} else if (instance.length) {
console.log('Object loaded');
// object of the user
console.log(instance[0]);
res.render('index', {object: instance[0]});
}
});
});
我可以在html中使用它:
.containerCustom
.head
h1
| #{object.name}
但是我不能在html页面中包含的javascript中使用它: 脚本。
alert(object.name);
怎么可能?
由于
答案 0 :(得分:2)
object
仅在您的Pug模板中定义,用于生成HTML,然后发送到浏览器。生成HTML后,此object
将被消耗并消失。它与页面的JS代码无关。
如果您希望这些数据在JS代码中可用,那么:从生成的页面向您的服务器发出另一个(Ajax)请求,要求提供相同的数据。
答案 1 :(得分:0)
这是因为您的响应保存在本地范围内,并且您没有将该响应传递给全局范围,您可以从外部访问它。 我只为你制作一个片段。检查一下,我希望这会对你有所帮助。 此外,如果您不了解范围,我建议您去阅读一些文章,例如w3school或this。此外,如果你不知道什么是异步请求也读了它们。
/* ############################### */
// So if you want to access response from your request you must save them or pass them
// This is one way to have access to your response outside by saving to global variable
// Creating variable where we will hold our response from request
// Global scope start here
var data = '';
function getResponse(res) {
// Here is opened Local scope where u have no access from outside
// and now here u have the response from your request
console.log('function data', res);
// you can do stuff here with that response
data = res;
}
setTimeout(function() {
var response = [1,2,3];
// Now here we will save response to our data so we can access it from global scope
// But remember that is async request
data = response;
console.log("local scope response ", response);
}, 1000);
setTimeout(function() {
console.log("global scope data", data); // here data hold ur response data from your async request
}, 1100);
/* ############################### */
// This is another way to have access to your response outside by passing it to function
function getResponse(res) {
// and now here u have the response from your request
console.log('function data', res);
// you can do stuff here with that response
data = res;
}
setTimeout(function() {
var response = [1,2,3];
// other way pass response to your function and do what u want with that data
getResponse(response);
console.log("bracked scope response ", response);
}, 1000);
答案 2 :(得分:0)
如评论中所示,由于@IsaacGodinez,此链接非常有用reference。 可以使用这行代码来获取整个对象:
var data = !{JSON.stringify(object).replace(/<\//g, '<\\/')};
或者,如果你只想要一个对象的元素:
var name = "#{object}";