我正在尝试获取我的 MySQL 表的数据并使用 EJS 在 HTML 中打印它们,但这不起作用。它告诉我 print not defined
。我该怎么办?
router.get('/data', function(req, res){
res.render('print', {req : req, res : res});
connection.query('SELECT * FROM users', function(err, result) {
if(err){
throw err;
} else {
for(x in result){
res.locals.print = result[x];
console.log(result[x]);
}
}
});
});
<!doctype html>
<html>
<body>
<div>
<%= print %>
</div>
</body>
</html>
最佳答案
在渲染中,您可以返回一个包含查询数据的 JSON 变量并显示在 View 中。 res.render
可以是最后一条指令。有些像这样:
var obj = {};
router.get('/data', function(req, res){
connection.query('SELECT * FROM users', function(err, result) {
if(err){
throw err;
} else {
obj = {print: result};
res.render('print', obj);
}
});
});
<body>
<table id="table" >
<thead>
<tr>
<th>Username</th>
<th>Password</th>
</tr>
</thead>
<tbody>
<% print.forEach(function (user) { %>
<tr>
<td><%= user.username %></td>
<td><%= user.password %></td>
</tr>
<% }) %>
</tbody>
</table>
</body>
</html>
关于mysql - 在 node.js (express) 中获取 MySQL 数据并使用 EJS 打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32628453/