[英]How to pass a JSON array object to a function from ejs
We have a Node.js application and when a user hits a certain route, a JSON array is fetched from an api(backend) and passed to my EJS template as an array object. 我们有一个Node.js应用程序,当用户点击某条路由时,会从api(后端)获取一个JSON数组并将其作为数组对象传递给我的EJS模板。
In the EJS template I have button which on click calls a Javascript function which does some computation on the JSON array object and displays the computed value on an html DIV element . 在EJS模板中,我有一个按钮,单击该按钮可以调用Javascript函数,该函数对JSON数组对象进行一些计算,并将计算出的值显示在html DIV元素上。 I don't know how to send the JSON array object from the ejs template to the javascript function.
我不知道如何从ejs模板向javascript函数发送JSON数组对象。 I see a similar question posted in stackoverflow but i dont see any correct solution for that
我在stackoverflow中看到了类似的问题,但是我没有看到任何正确的解决方案
The code for passing the JSON array object from node js router to ejs template looks like below . 将JSON数组对象从节点js路由器传递到ejs模板的代码如下所示。 Here 'data' is the JSON array object sent to ejs file(gallery.ejs) using res.render()
这里的“数据”是使用res.render()发送到ejs文件(gallery.ejs)的JSON数组对象
app.get(“/getBill”, function(req, res) {
bill(locationID,tableID, (error, billdata) => {
if (error) {
return console.log(error)
res.render("error")
}
else {
var data=billdata
res.render("gallery",{data:billdata})
}
})
});
I can access the JSON array object 'data ' in my ejs file (gallery.ejs) and iterate through it and access the elements in the JSON array. 我可以在我的ejs文件(gallery.ejs)中访问JSON数组对象'data',并对其进行迭代并访问JSON数组中的元素。
<% data.forEach(item => {%>
<div class="row ">
<div class="col-lg-8 col-sm-8">
<%=item.name%>
</div>
<div class="col-lg-4 col-sm-4 text-sm-right">
$<%=item.price/100%>
</div>
</div>
<%});%>
But I need to pass the JSON array object 'data' in the ejs file to a function on click of a button (see below). 但是我需要在单击按钮时将ejs文件中的JSON数组对象“数据”传递给函数(请参见下文)。 My goal is to access the JSON array object 'data' inside the function myFunction.
我的目标是访问函数myFunction中的JSON数组对象“数据”。
<button type="button" id="zeroperc" class="btn btn-outline-primary" onclick="myFunction()">0%</button>
How can I pass the JSON array object 'data' from ejs template to the function myFunction ()? 如何将JSON数组对象“数据”从ejs模板传递给函数myFunction()?
Simply add data
to the function argument using ejs: 只需使用ejs将
data
添加到function参数:
<button type="button" id="zeroperc" class="btn btn-outline-primary"
onclick="myFunction(<%=data%>)">0%</button>
Also, assuming data
is actually json, you might need to call JSON.parse(data)
from myFunction
before you can access it's properties. 另外,假设
data
实际上是json,则可能需要先从myFunction
调用JSON.parse(data)
,然后才能访问其属性。
Try this: 尝试这个:
<script type="text/javascript">
var data = <%=data%>;
</script>
<button type="button" id="zeroperc" class="btn btn-outline-primary"
onclick="myFunction(data)">0%</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.