html - 使用 postgres、nodejs 和 html 动态搜索查询
问题描述
我已经创建了一个 node.js 应用程序并成功连接到 Postgres 数据库。我还创建了一个包含输入文本字段和提交按钮的表单的 .html 文件。
当我在文本字段中输入内容并按下提交按钮时,我希望我的 node.js 应用程序使用输入的表单输入文本字段搜索该记录并将其显示在浏览器上。
我尝试使用请求参数并成功获取记录,但这不需要使用 HTML。我希望它在按钮的帮助下动态获取。
我还尝试在提交按钮上使用 onclick() 调用动态 URI(如“/abc/:xyz”),但没有得到任何结果。
node.js[处理“get”请求的端点]
app.get('/details/:regn_no', (req, res, next) => {
const regn_no = req.params.regn_no;
const results = [];
pg.connect(connectionString, (err, client, done) => {
if(err) {
done();
console.log(err);
return res.status(500).json({success: false, data: err});
}
const query = client.query('select * from vt_owner where regn_no=
$1',[regn_no]);
query.on('row', (row) => {
results.push(row);
});
query.on('end', () => {
done();
return res.json(results);
});
});
});
index.html [包含一个简单的 html 表单]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1,
shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>GET OWNER DETAILS</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-8">
<form id="form">
<div class="form-group" id="formID" >
<label for="regn_no">REGN_NO</label>
<input type="text" class="form-control" id="UserInput" placeholder="Enter
regn_no here" name="regn_no"><br>
<input type="button"
onclick="location.href='http://localhost:3000/details" id="submitButton"
value="Submit" />
</div>
</form>
</div>
</body>
</html>
```jquery
$(document).ready(function(){
$("#form").submit(function (event) {
$.post('/details', $("#form").serialize(), function (data) {
console.log(data) //data is the response from the backend
});
event.preventDefault();
});
})
当我输入“regn_no”并单击提交时。应用程序应获取与特定“regn_no”匹配的记录并显示它们。
解决方案
你在正确的轨道上。完全丢失表格,这里不需要。带有 onclick 处理程序的简单文本输入和按钮。使用 jQuery 调用您的端点并使用您收到的结果更新一个 div。类似于以下内容:
<html>
<body>
<input type="text" id="jqueryInput">
<button id="jqueryButton">Search</button>
<div id="jqueryOutput"></div>
<script>
$("jqueryButton").click(function() {
$.post("demo_test.asp", { regn_no: $("jqueryButton").val() }, function(res, status) {
$( "#jqueryOutput" ).html( res );
});
});
</script>
</body>
</html>
调整 URL 和传递参数的方式以适合您的 API。祝你好运。
推荐阅读
- java - getFilesDir() vs getExternalFilesDir(),哪个更推荐?
- pandas - 根据索引从一列 pandas 数据框转换为 3 列
- python - jupyter notebook 和 spyder 没有从 anaconda 提示符启动。但是它之前工作正常。它给了我以下错误:
- java - 在listview android中一起添加项目价格
- razor-pages - 在 asp.net core razor 页面上使用 LibVLCSharp
- java - 如何将此代码转换为 java 8 流?
- microsoft-teams - 是否可以为不使用中央服务提供商的 Microsoft Teams 创建自定义应用程序?
- c++ - 如何准确地对 C/C++ 代码进行基准测试?
- websocket - 海王星 | 小鬼蟒 | 使用 websocket 的并行查询
- r - 将数据库 ID 主题字符串重新分配为 R 中的因素