简体   繁体   English

如何在 EJS 中将 JSON 对象传递给内联 javascript

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

I just want to send EJS object to javascript function.我只想将 EJS 对象发送到 javascript 函数。 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我的 JavaScript 代码是

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) %> ' :你应该用单引号包裹你的 ejs 'stringified' 值,像这样' <%= JSON.stringify(book) %> '

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

And inside the JS function, parse it firstly:在JS函数内部,首先解析它:

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.您不能调用getBookDetails(<%=book%>)因为<%=book%>将被评估为[object Object]而不是{ name: "Wind in the willows, author: "Kenneth Grahame" }如您所需要.

You're on the right lines with using JSON.stringify but missed one crucial point: using <%= will escape html entities.您使用JSON.stringify是正确的,但错过了一个关键点:使用<%=将转义 html 实体。 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.您可以使用<%=book.name%>因为它应该输出一个字符串。

You should remove JSON.parse().console.log(bookString) .您应该删除JSON.parse().console.log(bookString)
It worked for me.它对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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