2016-02-17 59 views
1

我已经在一个名为.EJS模板中的项目的数组中创建了按钮/文本的html列表。如何将特定项目的id(item.id)传递给按钮的函数,以便将正确的数据发送到我的api?谢谢。如何使用EJS模板引擎将变量传递给嵌入式JavaScript?

<!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> 

回答

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

是你会怎么做,在我用每一个模板语言。看过文档后,看起来EJS是一样的

+0

什么是不工作呢?我发布的代码的输出标记是什么? – thedarklord47

+0

它表示“未捕获的ReferenceError:mxYbGAuc9p未定义”,因为该html编译为 supster

+0

什么是生成的HTML?请以我最初发布的方式运行代码,并发布产生的HTML。我们需要看看EJS正在制作的内容。将它添加为您的原始问题的编辑。 – thedarklord47