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.
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 . I don't know how to send the JSON array object from the ejs template to the javascript function. I see a similar question posted in stackoverflow but i dont see any correct solution for that
The code for passing the JSON array object from node js router to ejs template looks like below . Here 'data' is the JSON array object sent to ejs file(gallery.ejs) using res.render()
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.
<% 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). My goal is to access the JSON array object 'data' inside the function myFunction.
<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 ()?
Simply add data
to the function argument using ejs:
<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.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.