在node.js中获取MySQL数据(快速)并使用EJS打印 [英] Get MySQL data in node.js (express) and print using EJS

查看:127
本文介绍了在node.js中获取MySQL数据(快速)并使用EJS打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取我的MySQL表的数据并使用EJS以HTML格式打印它们,但这是行不通的.它告诉我print not defined.我该怎么办?

I'm trying to get the data of my MySQL table and print them in HTML using EJS, but this doesn't work. It tells me print not defined. What should I do?

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可以是最后一条指令.像这样:

In the render, you can return a JSON variable with the consulted data and show in the view. res.render can be the last instruction in this way. Some like this:

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>

这篇关于在node.js中获取MySQL数据(快速)并使用EJS打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆