简体   繁体   中英

How do I pass a JSON object to inline javascript In EJS

I just want to send EJS object to javascript function. I have tried below code but it 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 it didn't help. getBookDetails(<%=JSON.stringify(book) %>);

Please help me to find the mistake.

You should wrap your ejs 'stringified' value with single quotes, like this ' <%= JSON.stringify(book) %> ' :

<% books.forEach(function(book){ %>
    <button onclick="getBookDetails('<%= JSON.stringify(book) %>')"><%= book.name %></button>
<% }) %>

And inside the JS function, parse it firstly:

function getBookDetails(bookString){
   let book = JSON.parse(bookString)
   // now you can use the book object
}

You can't call getBookDetails(<%=book%>) because <%=book%> will get evaluated as [object Object] and not { name: "Wind in the willows, author: "Kenneth Grahame" } as you require.

You're on the right lines with using JSON.stringify but missed one crucial point: using <%= will escape html entities. Instead - use <%- like so:

<% books.forEach(function(book){ %>
    <button onclick="getBookDetails(<%-JSON.stringify(book)%>);"><%=book.name %></button>
<% }); %>

You're fine using <%=book.name%> because that should output a string.

You should remove JSON.parse().console.log(bookString) .
It worked for me.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM