【问题标题】:How to retrieve data from node.js (server side) using a variable from javascript (client side)?如何使用来自 javascript(客户端)的变量从 node.js(服务器端)检索数据?
【发布时间】:2020-02-07 19:27:19
【问题描述】:

我是 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);
    });
}

【问题讨论】:

  • 您必须向您的服务器发出 ajax 请求:$.get("your-serverside-script-url-here", { /* request data here */ }).then(function(response) { /* do something with the response from the server */ });
  • 欢迎来到 SO!是的,这是可能的。这个问题有点宽泛——你需要把它分成几个步骤。在接受某种参数或查询字符串的服务器上公开一个路由。让该路由使用其参数或查询字符串运行数据库查询。设置完成后,使用您的 jQuery 脚本发出 ajax 请求。所有这些都在其他地方讨论过——看起来你正在使用 ajax 步骤,所以我会投票关闭作为一个骗子。

标签: javascript node.js


【解决方案1】:

因为您无疑会有很多这样的按钮,所以我认为您会发现在外部项目上使用事件处理程序会更有效。然后,使用它通过 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(...);

您对该提取结果的处理取决于您发回的数据格式。另见:

【讨论】:

    【解决方案2】:

    您需要在某个地方安装一个节点服务器。它可以在您的本地主机或云中运行。知道服务器位置后,您需要向其端点发出 HTTP 请求,将变量作为参数发送,它可以在查询字符串 (URL) 上或请求正文中。调用它后,您会在回调中获得响应并在屏幕上显示数据。这是一个例子:

    async function makeRequest(param) {
      const result = await fetch(`http://localhost:3000/data?param1=${param}`);
    
      console.log(result.data);
    }
    

    这是一个 sn-p 向托管在 localhost:3000 上的服务器发出请求,它提供路径 /data 并接收 param 作为 查询字符串强>。

    在您的服务器端,您需要使用http 节点内置库创建服务器或使用框架作为express

    【讨论】:

      猜你喜欢
      • 2018-03-04
      • 1970-01-01
      • 2020-11-13
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 2013-06-09
      相关资源
      最近更新 更多