gpt4 book ai didi

javascript - 使用 Node.js 和 Express 将 JSON 数据集显示为表格

转载 作者:太空狗 更新时间:2023-10-29 15:48:59 32 4
gpt4 key购买 nike

首先,我想指出我是 Node.JS 的新手。我正在尝试使用 NodeJS 制作包含多个表格和信息的页面。我的问题是,我无法将 SQL 查询的结果放入 HTML 表中。目前,我使用 express .send 将数据发送到 HTML 页面中。

我使用的代码:

    var http = require('http');
http.createServer(function(req, res) {});
var mysql = require("mysql");
var express = require('express');
var app = express();
console.log('Creating the http server');
con.query('SELECT id ,name FROM customer', function(err, rows, fields)
{
console.log('Connection result error '+err);
console.log('num of records is '+rows.length);

app.get('/', function (req, res) {
res.send(rows);
});

});

app.listen(3002, function () {
console.log('Example app listening on port 3000!');
})

这会在我的 HTML 页面上打印我的 sql 语句中的所有数据:

{"id":"1","name":"Robert"}
{"id":"2","name":"John"}
{"id":"3","name":"Jack"}
{"id":"4","name":"Will"}

我想要的结果是:

id              Name
1 Robert
2 John
3 Jack
4 Will
..etc

这甚至可以在 Node JS 中实现吗?

最佳答案

与 Jade 类似,您可以使用 Embedded JS

<table>
<tr>
<th>id</th><th>Name</th>
</tr>

<% for (var i = 0; i < data.length; i++) { %>
<tr>
<td><%= data[i].id %></td>
<td><%= data[i].name %></td>
</tr>
<% } %>
</table>

这将遍历对象数组(我已将其保存为 data 并基于它填充一个表。

关于javascript - 使用 Node.js 和 Express 将 JSON 数据集显示为表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34809975/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com