如何将 JSON 对象传递给内联 javascript 在 EJS 中
How do I pass a JSON object to inline javascript In EJS
我只想将 EJS 对象发送到 javascript 函数。我试过下面的代码,但没有用。
<% books.forEach(function(book){ %>
<button onclick="getBookDetails(<%=book %>);" > <%=book.name %></button>
<% }); %>
我的JavaScript密码是
function getBookDetails(book){
//using book object
}
我尝试了以下内容also.But但没有帮助。getBookDetails(<%=JSON.stringify(book) %>);
请帮我找出错误。
您不能调用 getBookDetails(<%=book%>)
,因为 <%=book%>
将被计算为 [object Object]
而不是您需要的 { name: "Wind in the willows, author: "Kenneth Grahame" }
。
您使用 JSON.stringify
是正确的,但错过了一个关键点:使用 <%=
将转义 html 个实体。相反 - 使用 <%-
像这样:
<% books.forEach(function(book){ %>
<button onclick="getBookDetails(<%-JSON.stringify(book)%>);"><%=book.name %></button>
<% }); %>
你可以使用 <%=book.name%>
因为它应该输出一个字符串。
你应该用单引号将你的 ejs 'stringified' 值括起来,像这样 '<%= JSON.stringify(book) %>':
<% books.forEach(function(book){ %>
<button onclick="getBookDetails('<%= JSON.stringify(book) %>')"><%= book.name %></button>
<% }) %>
在JS函数内部,先解析:
function getBookDetails(bookString){
let book = JSON.parse(bookString)
// now you can use the book object
}
你应该删除 JSON.parse().console.log(bookString)
。
它对我有用。
我只想将 EJS 对象发送到 javascript 函数。我试过下面的代码,但没有用。
<% books.forEach(function(book){ %>
<button onclick="getBookDetails(<%=book %>);" > <%=book.name %></button>
<% }); %>
我的JavaScript密码是
function getBookDetails(book){
//using book object
}
我尝试了以下内容also.But但没有帮助。getBookDetails(<%=JSON.stringify(book) %>);
请帮我找出错误。
您不能调用 getBookDetails(<%=book%>)
,因为 <%=book%>
将被计算为 [object Object]
而不是您需要的 { name: "Wind in the willows, author: "Kenneth Grahame" }
。
您使用 JSON.stringify
是正确的,但错过了一个关键点:使用 <%=
将转义 html 个实体。相反 - 使用 <%-
像这样:
<% books.forEach(function(book){ %>
<button onclick="getBookDetails(<%-JSON.stringify(book)%>);"><%=book.name %></button>
<% }); %>
你可以使用 <%=book.name%>
因为它应该输出一个字符串。
你应该用单引号将你的 ejs 'stringified' 值括起来,像这样 '<%= JSON.stringify(book) %>':
<% books.forEach(function(book){ %>
<button onclick="getBookDetails('<%= JSON.stringify(book) %>')"><%= book.name %></button>
<% }) %>
在JS函数内部,先解析:
function getBookDetails(bookString){
let book = JSON.parse(bookString)
// now you can use the book object
}
你应该删除 JSON.parse().console.log(bookString)
。
它对我有用。