我正在学习如何将node.js 与mysql 一起使用。我试图找到一些好的文档,但徒劳无功。我现在可以在浏览器中显示 mysql 数据,但我想在某个时候通过我的 index.html 和 css 文件来处理它。
这是我的 app.js:
// moduels
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('bodyParser')
//
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: false}));
// connect to database
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "BathBombs_DB"
});
// routes
app.get('/', function(request, response){
console.log('GET request received at /')
con.query("SELECT * FROM customers", function (err, result) {
if (err) throw err;
else{
response.send(result)
}
});
});
// listen for trafic and display on localhost:9000
app.listen(9000, function () {
console.log('Connected to port 9000');
});
我的 index.html 网站如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="/" method="POST">
<table type="text" name="firstname" ></table>
</form>
</body>
</html>
您必须进行 ajax 调用才能从服务器获取结果并使用 javascript 与 HTML 内容绑定,如下所示:
HTML模板
<table id="tableData" class="table table-fixed">
<thead>
<tr>
</tr>
</thead>
<tbody class="tbody" >
</tbody>
这是进行 ajax 调用的脚本
$(document).ready(() => {
$.ajax({
url: "http://localhost:9000/list",
method: 'GET',
success: function(response){
if(response.rows.length > 0){
for(let index = 0; index < response.rows.length; index++) {
var newRow = $("<tr>");
var cols = "";
var firstname = '';
var lastname = '';
var gender = '';
cols += '<td> '+ response.rows[index].firstname +'</td>';
cols += '<td> '+ response.rows[index].lastname +'</td>';
cols += '<td> '+ response.rows[index].gender+'</td>';
newRow.append(cols);
$("#tableData .tbody").append(newRow);
}
}
}
})
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)