我对 Node.js 很陌生,正在尝试学习该语言。
我想知道是否可以从 html 页面获取一个变量并使用该变量在数据库中查找一行并在 html 中查看该数据。
我打算做的是有一个表格,我可以在其中单击信息图标,该图标将引导我查看该行数据的详细信息。
我已经从下面的代码中获取了我想要引用的数据,但我不知道如何将该变量传递到服务器端并继续处理。
const icon = document.getElementsByClassName("iconButton");
icon.addEventListener('click', myFunction(this));
function myFunction(x){
var $row;
var $title;
var $time;
$(".iconButton").click(function() {
$row = $(this).closest("tr");
$title = $row.find(".topic").text();
$time = $row.find(".time").text();
alert($title);
alert($time);
});
}
最佳答案
由于您无疑会拥有很多这样的按钮,因此我认为您会发现在外部项目上设置事件处理程序会更有效。然后,使用它通过 Fetch API 发出 HTTP 请求。
因此,在您的 HTML 中,执行如下操作:
<table>
<thead>
<tr>
<th>Complaint Title</th>
<th>Created At</th>
<th>Reported By</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr data-complaint-id="12345">
<td>...</td>
<td>...</td>
<td>...</td>
<td>
<button class="info">🛈</button>
</td>
</tr>
</tbody>
</table>
请注意,我在此处的整行上设置了投诉 ID。这是为了轻松提供整行的数据,因为您将来可能会添加其他操作。
现在,在您的脚本中,将事件处理程序添加到表中:
document.querySelector('table').addEventListener('click', (e) => {
if (e.target.matches('[data-complaint-id] .info')) {
// If an info button is a child of a row with a complaint ID, then do something.
}
});
最后,在 if
block 中发出 HTTP 请求:
const complaintId = this.target.closest('[data-complaint-id]').dataset.complaintId;
fetch('https://example.com/complaints/' + encodeURIComponent(complaintId)).then(...);
您对获取结果的处理取决于您发回的数据格式。另请参阅:
关于javascript - 如何使用 javascript(客户端)中的变量从 node.js(服务器端)检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60119881/