在EJS中循环遍历JSON [英] Loop through JSON in EJS

查看:634
本文介绍了在EJS中循环遍历JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的EJS中有代码,

I have codes in EJS below,

<script>
    var row =<%-JSON.stringify(data)%>
    console.log(row);
</script>
<% for(var i=0; i<JSON.stringify(data).length; i++) {%>
   <tr>
     <td>
       <%= JSON.stringify(data)[i].id%>
     </td>
   </tr>
<% } %>

该行的输出是正确的,由3个对象组成的数组,每个对象具有属性ID,名称等.我可以操纵该行以在JS中填充表格.但是,我想知道是否有一种方法可以通过上述方式完成它?

output of row is correct, an array of 3 objects, each with properties id, name etc.. I can manipulate the row to popuate the table in JS. However, I am wonderring whether there is a way to allow it be done in the above manner?

当我运行上面的代码时,JSON.stringify(data).length不是3,而是整个字符串的长度.

When I run the code above, JSON.stringify(data).length is not 3, but rather the length of the whole string.

另一个问题是我何时尝试添加

Another questions is when I try to add

<%Alert('t'); %>或<%window.alert('t'); %>,它给了我未定义"错误...

<% alert('t'); %> or <% window.alert('t'); %>, it gives me 'not defined' error...

帮助表示赞赏.

问候 锤子

推荐答案

JSON.stringify返回String.因此,例如:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

将返回等于:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

作为String值.

因此,当您拥有

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

最终看起来像是:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

可能不是您想要的.您可能想要做的事情是这样的:

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

这将输出下表(使用上面的示例data):

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

这篇关于在EJS中循环遍历JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆