【发布时间】:2019-12-23 02:13:14
【问题描述】:
我正在尝试从 html 表中检索数据并将其插入 MySQL 数据库。我已经能够做相反的事情,即从数据库中检索信息并使用 ejs 模板将其显示在同一个表中。我也可以将原始/JSON 数据插入 MySQL,但我无法从同一个表中提取数据,因为我无法从服务器端引用该表(与正文解析器处理表单数据的方式相同)。
我在网上搜索过,所有教程都只是使用 json 数据插入数据库,没有人先从 html 表中检索数据。
通过下面的代码,我可以使用普通的 javascript 循环遍历表数据。
var table = document.getElementById('vehiclesTB');
for (var i = 1; i < table.rows.length; i++) {
if (table.rows[i].cells.length) {
var vehicleTag = (table.rows[i].cells[0].textContent.trim());
}
}
如何将检索数据从 html 表传递到我的控制器(服务器端)?我无法直接从我的服务器文件 (app.js) 中引用 html 表。
我的 app.js 文件:
var express = require('express')
, routes = require('./routes')
, controls = require('./routes/controls')
, http = require('http')
, path = require('path');
var app = express();
var mysql = require('mysql');
var bodyParser =require("body-parser");
var pool = mysql.createConnection({
connectionLimit: 100,
host: 'localhost',
database: 'vehicluster',
user: 'motor',
password: '',
debug: false
});
pool.connect();
// all environments
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.post('/vehicle', controls.vehicle);
//Middleware
app.listen(8080)
我的 controls.js 文件。
exports.vehicle = function(req, res){
var table = document.getElementById('vehiclesTB');//how to read this
table in ejs
for (var i = 1; i < table.rows.length; i++) {
if (table.rows[i].cells.length) {
var vehicleTag = (table.rows[i].cells[0].textContent.trim());
var vehicleMake = (table.rows[i].cells[1].textContent.trim());
var vehicleModel = (table.rows[i].cells[2].textContent.trim());
var price = (table.rows[i].cells[3].textContent.trim());
var quantity = (table.rows[i].cells[4].textContent.trim());
}
}
var sql = 'insert into Vehicle(make, model, price, quantity) values
(?,?,?,?,?)';
pool.query(sql,[vehicleMake, vehicleModel, price, quantity],
(err,data)=>{
if(err){
console.log(err);
return
}else{
console.log(data);
}
};
HTML表格正在显示相关项目(表格),将表格数据放入mysql数据库。我已经可以检索到表:
<div style="overflow-x: auto;">
<table id="customers">
<tbody id="mytbody">
<tr>
<th>Make</th>
<th>Model</th>
<th>price</th>
<th>quantity</th>
</tr>
<tr>
<th>toyota</th>
<th>camry</th>
<th>200</th>
<th>5</th>
</tr>
<tr>
<th>honda</th>
<th>civic</th>
<th>400</th>
<th>7</th>
</tr>
</tbody>
</table>
</div>
如您所料,我收到错误,getElementById 是客户端,空值等,数据库未更新。大多数在线教程都显示相反的情况,即将数据库值插入到 html 表中,而不是相反。任何有关真实表格示例/路线的帮助将不胜感激。
【问题讨论】:
标签: javascript html mysql node.js ejs