简体   繁体   English

使用ejs组件将数据从js发送到html

[英]Sending data from js to html with ejs components

I've just begun to learn about JS and node.js. 我刚刚开始学习JS和node.js。 I've been trying to do some practicing on sending data from a DB in MySQL to the html via ejs components. 我一直在尝试通过ejs组件将数据从MySQL中的数据库发送到html上进行一些练习。 I tried using ejs.render(data, {data: something_from_DB}); 我尝试使用ejs.render(data,{data:something_from_DB}); to send fetched information(something_from_DB), identified by "data". 发送获取的信息(something_from_DB),该信息由“数据”标识。 I then used the identifier "data" in the ejs code in html, but it'd complain that data is not defined in the html file. 然后,我在html的ejs代码中使用了标识符“ data”,但是它抱怨html文件中未定义数据。

Here's the js code. 这是js代码。

var mysql = require('mysql');
var fs = require('fs');
var http = require('http');
var express = require('express');
var ejs = require('ejs');
var app = express();
app.use(app.router);

var client = mysql.createConnection({
    user: 'username',
    password: 'password',
    database: 'database_name'
});

app.get('/', function(req, res){

    fs.readFile('list.html', 'utf8', function(error, data){
        client.query('SELECT * FROM test_table', function(error, results){
            console.log(results);
            res.send(ejs.render(data), {data: results});
        });
    });
});

And here's the portion from list.html 这是list.html中的部分

<% data.forEach(function(item, index){ %>
<tr>
    <td><%= item.id %></td>
    <td><%= item.name %></td>
    <td><%= item.phone_no %></td>
</tr>
<% }); %>

When I print the results, I get: 当我打印结果时,我得到:

[ RowDataPacket { id: 1, name: 'PETER', phone_no: '0100000000' } ]

which looks fine. 看起来不错。 I'm looking to pass this with "data" but I don't think this is happening. 我希望通过“数据”传递它,但我不认为这种情况正在发生。

Please do correct me if I'm using words that are out of context. 如果我使用的语境不正确,请纠正我。

我认为有一个简单的错误。只需尝试一下。

      res.render('ejs file name',{data: results,});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM