How do I pass a JSON object to inline javascript In EJS -
i want send ejs object javascript function. have tried below code didn't work.
<% books.foreach(function(book){ %> <button onclick="getbookdetails(<%=book %>);" > <%=book.name %></button> <% }); %>
my javascript code is
function getbookdetails(book){ //using book object }
i have tried following stuff also.but didn't help.getbookdetails(<%=json.stringify(book) %>);
please me find mistake.
you can't call getbookdetails(<%=book%>)
because <%=book%>
evaluated [object object]
, not { name: "wind in willows, author: "kenneth grahame" }
require.
you're on right lines using json.stringify
missed 1 crucial point: using <%=
escape html entities. instead - use <%-
so:
<% books.foreach(function(book){ %> <button onclick="getbookdetails(<%-json.stringify(book)%>);"><%=book.name %></button> <% }); %>
you're fine using <%=book.name%>
because should output string.
Comments
Post a Comment