小编典典

如何使用EJS模板引擎将变量传递给内联javascript?

ajax

我已经从.EJS模板中称为项的数组中创建了按钮/文本的html列表。如何将特定项目的ID(item.id)传递给按钮的功能,以便将正确的数据发送到我的api?谢谢。

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Menu</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script type="text/javascript">

    function print(id) {
        $.ajax({
          url: "https://www.example.com/api/1/print",
          type: "POST",
          data: {
            "item_id": id
          },
          dataType: "json",
          success: function (result) {
            alert(result);
          },
          error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
          }
        });
      };
    </script>
  </head>
  <body>
    <h2>Menu</h2>
    <ul>
        <% for(item of items) { %>
          <li>
            <button onclick="print(item.id)">PRINT</button>
            <%= item.name %> - <%= item.id %>
          </li>
        <% } %>
    </ul>
  </body>
</html>

阅读 380

收藏
2020-07-26

共1个答案

小编典典

<button onclick="print('<%= item.id %>')">PRINT</button>

这就是我将要使用的每种模板语言所采用的方法。看完文档后,看来EJS是一样的

2020-07-26