Ham*_*mer 4 ejs node.js express
我在 express+EJS 中有一些代码,
1) 在 app.js 中,创建了 mongo 集合对象,
app.locals.userCollection = db.get('userData');
Run Code Online (Sandbox Code Playgroud)
2) 在 user.js express 路由文件中,我从这个数据库连接中获取数据,并希望将其传递给 EJS 进行渲染,
exports.list = function(req, res){
req.app.locals.userCollection.find({},function(err , returnValue){
if(returnValue.length>0){
res.render('user', res.locals.returnValue);
}
return err;
});
Run Code Online (Sandbox Code Playgroud)
};
3)在 user.ejs 我尝试使用访问它
<div><script>
var test = <%- returnValue %>;
Run Code Online (Sandbox Code Playgroud)
它给了我 returnValue is not defined 错误。
我可以知道如果我想访问 returnValue[0].attr1,我应该在路由和 EJS 中编码什么?
问候锤子
您可以尝试以下操作:
在 Node.js 中:
res.render('user', data: res.locals.returnValue);
在 EJS 中:
<script type='text/javascript'>
var rows =<%-JSON.stringify(data)%>
alert(rows);
</script>
Run Code Online (Sandbox Code Playgroud)
如果你想循环,rows那么你不应该使用,JSON.stringify()因为它将你的对象转换为String你可以尝试执行以下操作(如果服务器放置的数据是数组对象,则以下代码有效)。
<script type='text/javascript'>
<% data.forEach(function(dataRow, idxOfRow, orgnlAryObject) {
// You can directly use the dataRow to get each row from the array Object `data`
//alert(JSON.stringify(dataRow)); // <== You can try this
}); %>
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4689 次 |
| 最近记录: |