我在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);
});
}发布于 2020-02-07 19:36:31
因为您无疑会有很多这样的按钮,我想您会发现在外部项上有一个事件处理程序会更有效。然后,使用它通过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块中,发出您的HTTP请求:
const complaintId = this.target.closest('[data-complaint-id]').dataset.complaintId;
fetch('https://example.com/complaints/' + encodeURIComponent(complaintId)).then(...);您如何处理该获取结果取决于您发送的数据格式。另请参阅:
https://stackoverflow.com/questions/60119881
复制相似问题