我希望当单击“发送到数据库”按钮时,将表单中的数据发送到数据库并在表单中输出。现有表格的新行。
我有一个表格,下面有一个按钮,它依次调用一个表单将数据发送到数据库(至少这是它的意思)
<!--Actually the button calling the form and the table-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mine_contract</title>
<link href="new.css" rel="stylesheet"/>
<script src="script.js" defer></script>
</head>
<body>
<table id="mine_info">
<tr>
<th>№</th>
<th>Number</th>
<th>Name</th>
<th>Address</th>
<th>Full name of the director</th>
<th>Phone number</th>
</tr>
<tr>
<td><p>1</p></td>
<td><p>1</p></td>
<td><p>Example name</p></td>
<td><p>Example address</p></td>
<td><p>Full name director</p></td>
<td><p>+00000000000</p></td>
</tr>
</table>
<div class="popup">
<div class="popup__container">
<div class="popup__wrapper">
<div id="wrapper">
<form action="(I don't understand if there should be something here)" method="POST" class="form">
<button class="exit" class="exit" id="closeButton" onclick="delRow()">х</button>
<div class="string">
<label for="id">№:</label>
<input type="number" id="id" name="id" required>
</div>
<div class="string">
<label for="N_m">Number:</label>
<input type="text" id="N_m" name="n_m" required>
</div>
<div class="string">
<label for="name">Name:</label>
<input type="text" id="name" name="name_m" required>
</div>
<div class="string">
<label for="Adr">Address:</label>
<input type="text" id="Adr" name="Adr_m" >
</div>
<div class="string">
<label for="Full_name">Full name of the director:</label>
<input type="text" id="Full_name" name="director" required>
</div>
<div class="string">
<label for="Phone">Phone number:</label>
<input type="tel" id="Phone" name="Phone_number" placeholder="Например +00000000000" required>
</div>
<button type="submit" name = "submit" id="contact">Send to DB</button>
</form>
</div>
</div>
</div>
</div>
<button id="button" class="button" onclick="addRow()">Open the form</button>
</body>
</html>
我使用脚本调用表单
//script.js
const button = document.querySelector('#button');
const closeButton = document.querySelector('#closeButton');
const form = document.querySelector('.form');
const popup = document.querySelector('.popup');
button.addEventListener('click', () => {
form.classList.add('open');
popup.classList.add('popup_open');
});
closeButton.addEventListener('click', () => {
form.classList.remove('open');
popup.classList.remove('popup_open');
});
我还在 Node.js 上编写了一个后端(如果你可以这样称呼它的话)。
const Pool = require('pg').Pool
const pool = new Pool({
user: '',
host: '',
database: '',
password: '',
port: 5432,
})
const getMineinfo = (request, response) => {
pool.query('SELECT * FROM mine_info', (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
const createRow = (request, response) => {
const { n_mine, name_mine, adress, full_name_of_direcor, phone_number } = request.body
pool.query('INSERT INTO mine_info (n_mine, name_mine, adress, full_name_of_direcor, phone_number) VALUES ($1, $2, $3, $4, $5) RETURNING *', [n_mine, name_mine, adress, full_name_of_direcor, phone_number], (error, results) => {
if (error) {
throw error
}
response.status(201).send(`User added with ID: ${results.rows[0].id}`)
})
}
module.exports = {
getMineinfo,
createRow,
}//Variables from another file
//another file in which, there are these variables
const express = require('express')
const bodyParser = require('body-parser')
const db = require('./queries')
const app = express()
const port = 3000
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.get('/', (request, response) => {
response.json({ info: 'Node.js, Express, and Postgres API' })
})
app.get('/mine_info', db.getMineinfo)
app.post('/mine_info', db.createRow)
app.listen(port, () => {
console.log(`App running on port ${port}.`
)})//it works I get the data in the form of JSON by reference http://my-data:3000/mine_info/
据我了解并试图弄清楚,对于我想要的东西,我需要发出 AJAX 请求。 但我不明白该怎么做(也许我很愚蠢),但我请你理解这是我第一次尝试制作这样的网络应用程序。
我试图弄清楚 AJAX 文档。我试图通过 fetch 来解决我的问题,但在那里我遇到了如何克服 CORS 的问题。我还尝试通过 XMLHttpRequest 解决我的问题,但我没有弄清楚,在我看来它是一个过时的解决方案(也许不是)。我请你帮助我,也许并不是所有事情都像我看起来那么困难,我对那些读过这个长问题的人表示非常感谢。
您需要从输入字段收集数据,并向该路由发出 POST 请求并传递该数据:
app.post('/mine_info'
所以,你需要:
您不需要表单属性,因为您使用 JavaScript 手动发出请求,但添加 CSS 标识符来获取表单元素)
<form id="myForm" class="form">
获取表格:
const form = document.getElementById('myForm');
添加提交事件监听器:
form.addEventListener('submit', async (e) => {
e.preventDefault();
现在您需要获取每个输入字段的值。
您可以使用 DOM 选择器选择每个元素,但是有一个单行代码可以使用表单数据自动为您执行此操作(请参阅本指南以获取更多信息以及是否还需要发送文件:使用 FormData 对象 :
将表单元素传递给表单数据构造函数
new FormData(form)
现在,您将发出 JSON 请求,因此将所有条目转换为 JSON 对象,该对象将被发布。 在服务器上,
bodyParser
将处理该JSON请求(如果你想添加一个文件,那么你需要发布多部分请求,并且你需要多部分处理中间件,例如multer)
const data = Object.fromEntries(new FormData(form).entries());
使用原生
fetch
发出 JSON 请求,因此将 JSON 添加为内容类型,并将 JSON 对象编码为 body
参数(有关更多信息,请参阅本指南:使用 Fetch API)
try {
const response = await fetch('/mine_info', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
// parse response: .text() is for text format, use .json() for JSON response
const result = await response.text();
console.log('result', result)
// show the message in the DOM
// ..
} catch (error) {
// show some error message in the DOM
console.log('err: ', error);
}
(注意:您的服务器发送带有
res.send
的响应,这意味着它是文本格式,因此您需要使用 .text()
,但是如果您使用 res.json
代替,那么您需要使用 .json()
来解析回应)
完整代码:
const form = document.getElementById('myForm');
form.addEventListener('submit', async(e) => {
e.preventDefault();
const data = Object.fromEntries(new FormData(form).entries());
console.log('data to post: ', data);
try {
const response = await fetch('/mine_info', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
const result = await response.text();
console.log('result', result)
// show the message in the DOM
// ..
} catch (error) {
// show some error message in the DOM
console.log('err: ', error);
}
});
<form id="myForm">
<button class="exit" class="exit" id="closeButton" onclick="delRow()">х</button>
<div class="string">
<label for="id">№:</label>
<input type="number" id="id" name="id" required>
</div>
<div class="string">
<label for="N_m">Number:</label>
<input type="text" id="N_m" name="n_m" required>
</div>
<div class="string">
<label for="name">Name:</label>
<input type="text" id="name" name="name_m" required>
</div>
<div class="string">
<label for="Adr">Address:</label>
<input type="text" id="Adr" name="Adr_m" >
</div>
<div class="string">
<label for="Full_name">Full name of the director:</label>
<input type="text" id="Full_name" name="director" required>
</div>
<div class="string">
<label for="Phone">Phone number:</label>
<input type="tel" id="Phone" name="Phone_number" placeholder="Например +00000000000" required>
</div>
<button type="submit" name = "submit" id="contact">Send to DB</button>
</form>