我试图获得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变量,其中包含所咨询的数据并显示在视图中。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>