Javascript 使用 Node.js 和 Express 将 JSON 数据集显示为表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34809975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Displaying a JSON dataset as a table with Node.js and Express
提问by Rahul Sharma
First of all, I would like to point out that I'm very new to Node.JS. I'm trying to use NodeJS to make a page containing multiple tables and info. My problem is, that I can't get the result from the SQL query into an HTML table. Currently I .send
the data into an HTML page using express.
首先,我想指出我对 Node.JS 非常陌生。我正在尝试使用 NodeJS 制作一个包含多个表格和信息的页面。我的问题是,我无法将 SQL 查询的结果放入 HTML 表中。目前我.send
使用 express 将数据转换为 HTML 页面。
Code that I use:
我使用的代码:
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!');
})
This prints all the data from my sql statement on my HTML page:
这会在我的 HTML 页面上打印我的 sql 语句中的所有数据:
{"id":"1","name":"Robert"}
{"id":"2","name":"John"}
{"id":"3","name":"Hyman"}
{"id":"4","name":"Will"}
what I would like to have as result is :
我想要的结果是:
id Name
1 Robert
2 John
3 Hyman
4 Will
..etc
Is this even possible to do in Node JS?
这甚至可以在 Node JS 中做到吗?
采纳答案by Urknecht
I would recommend you look at Jade. It is a template engine for node js which can be used to create html pages. It is easy to use and very flexible.
我建议你看看Jade。它是 node js 的模板引擎,可用于创建 html 页面。它易于使用且非常灵活。
A good tutorial is found here. It shows you how to create a simple Website with Node, Express and Jade and is a good starting Point in my opinion.
一个很好的教程可以在这里找到。它向您展示了如何使用 Node、Express 和 Jade 创建一个简单的网站,我认为这是一个很好的起点。
To solve your problem with Jade there are several answers in stackoverflow like here.
为了解决您的 Jade 问题,stackoverflow 中有几个答案,例如这里。
回答by Simon Legg
Similar to Jade you could use Embedded 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>
This would iterate through an array of objects (which I have saved as data
and populate a table based on that.
这将遍历一组对象(我已将其另存为data
并基于该数组填充表。