javascript - 如何使用 javascript(客户端)中的变量从 node.js(服务器端)检索数据?

标签 javascript node.js

我对 Node.js 很陌生,正在尝试学习该语言。

我想知道是否可以从 html 页面获取一个变量并使用该变量在数据库中查找一行并在 html 中查看该数据。

我打算做的是有一个表格,我可以在其中单击信息图标,该图标将引导我查看该行数据的详细信息。

我已经从下面的代码中获取了我想要引用的数据,但我不知道如何将该变量传递到服务器端并继续处理。

Table

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/

相关文章:

javascript - 服务从 Controller 获取 $http API 请求的 URL - Angular.js

Node.js Clustering- Forking,实际使用了多少内存?

node.js - CSSO npm 不工作,而其他人是

mysql - 如何将两个模型与 sequelize 相关联? (1 :n) and (m:n)

带有默认值的 JavaScript JSON API 解析器?

node.js - 需要有关 Socket.io.js 加载失败的帮助

javascript - 理解 Complex inArray 三元运算符

javascript - Angular 4嵌套formArray/formGroup将数据库查询中的值放回表单中

javascript - 如何将数据从弹出脚本发送到crossrider中的background.js?

javascript - 使用 d3 js 库的 data 方法将事件绑定(bind)到动态生成的内容