如何使用EJS模板引擎将变量传递给内联javascript? [英] How do I pass a variable to inline javascript using EJS templating engine?
本文介绍了如何使用EJS模板引擎将变量传递给内联javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经从.EJS模板中名为items的数组中创建了一个按钮/文本的html列表。如何将特定项目的id(item.id)传递给按钮的功能,以便将正确的数据发送到我的api?谢谢。
I've created a html list of buttons/text from an array called items in an .EJS template. How do I pass the specific item's id (item.id) to the button's function so I can send the right data to my api? Thanks.
<!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>
推荐答案
<button onclick="print('<%= item.id %>')">PRINT</button>
是你用我使用过的每种模板语言的方法。在查看文档后,似乎EJS是相同的
is how you would do it in every templating language I have used. After looking at the docs, it appears EJS is the same
这篇关于如何使用EJS模板引擎将变量传递给内联javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文