我是Node.js的新手。我可以使用Node.js将我的HTML数据插入MySQL,但我无法从MySQL获取数据并将其输出到我的HTML页面。我已经发布了我在下面完成的代码。我正在努力将数据放入我的HTML页面。
的index.html
<form action="/" method="post">
<input id="name" type="text" name="name" placeholder="Type your name...">
<input id="message" type="text" name="message" placeholder="Type message...">
<input class="submit_message" type="submit" value="Send">
</form>
server.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', express.static(__dirname + '/'));
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mywebsite"
});
connection.connect();
app.get('/', function (req, res) {
connection.connect();
connection.query('SELECT * FROM users', function(err, rows, fields) {
connection.end();
if (err) throw err;
console.log("Data displayed");
});
});
app.post('/', function(req, res) {
var username = req.body.name;
var usermessage = req.body.message;
connection.query("INSERT INTO `users` (Name, Message) VALUES (?,?)", [username.toString(), usermessage.toString()], function(err, result) {
if(err) throw err;
//Output results
console.log(result.affectedRows + ' rows updated. ID is ' + result.insertId);
});
res.sendFile(__dirname + '/index.html');
});
app.listen(3000, function () {
console.log('Connected to port 3000');
});
答案 0 :(得分:0)
您可以安装EJS包,在html中使用Javascript并操纵后端的数据。详细了解点击here.
运行以下命令安装并保存ejs包:
npm install ejs -s
将 Index.html 重命名为 Index.ejs
设置引擎:
app.set("view engine", "ejs");
我认为你的 app.get 应该是这样的:
app.get('/', function (req, res) {
connection.query('SELECT * FROM users', function(err, result, fields) {
connection.end();
if (err) throw err;
console.log("Data displayed");
res.render("Index", { result: result });
});
});
res.render("Index", {result: result});
会调用你的Index.ejs传递一个带有你数据的Json。
你的Indes.ejs会是这样的:
<table id="tblData" class="table table-bordered table-hover">
<thead class="thead-inverse">
<tr>
<th data-column-id="Name">
Name
</th>
<th data-column-id="Message">
Message
</th>
</tr>
</thead>
<tbody></tbody>
</table>
最后,您可以添加<script></script>
和Jquery DataTables
//Declare the var with the data
var Result = <%- JSON.stringify(result) %>;
var TableData = null;
$(function () {
function ajusTables() {
$('.table').css('width', '100%');
$('.dataTables_scrollHeadInner').css('width', '100%');
}
TableData = $('#tblData').DataTable({
"serverSide": false,
"drawCallback": function (settings) {
ajusTables();
},
"scrollX": true,
"processing": true,
"paging": true,
"lengthChange": false,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"deferRender": true,
"columns": [
{ "data": "Name" },
{ "data": "Message" },
],
"order": [0, "asc"]
});
console.log(Result);
TableData.rows.add(Result)
TableData.draw();
});
</script>
这种使用数据的方法对我来说很有用。
希望对你有所帮助。