gpt4 book ai didi

javascript - 如何将 JSON 对象传递给 EJS javascript 循环?

转载 作者:行者123 更新时间:2023-12-03 02:32:27 24 4
gpt4 key购买 nike

这里需要一些帮助,我正在尝试将 Json 对象作为 myVar 传递到下面的 home.ejs 文件。我应该如何将值分配给名为 data 的变量?

<table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">CSI ID</th>
<th scope="col">App Name</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<!-- Below throws the error -->
<% var data = <%= myVar %>
<% for (var i = 0; i < data.length; i++) { %>
<tr>
<td><%= data[i].id %></td>
<td><%= data[i].name %></td>
</tr>
<% } %>
</tbody>
</table>

Error Message

Could not find matching close tag for "<%".> 

app.js

此处“项目”输出 JSON 数据

  app.get("/",function(req,resp) { 

client.projects.getAll()
.then(function(projects){
console.log(projects); //buildList.build is an array of builds, from most recent to the count parameter
myJsonData = projects;

});
resp.render('nav', {"page":"home.ejs","myVar":myJsonData});
});

最佳答案

res.render接受要渲染的 View 名称和一个可选参数,该参数是包含 View 局部变量的对象。这意味着如果第二个参数是像这样的对象 { name: "value"} 那么你可以从 ejs View 访问变量 name 。你的代码应该是:

路由处理程序:

app.get("/",function(req,resp) { 

client.projects.getAll().then( function(projects) {

// render response when you get projects populated
resp.render('nav', { page: "home.ejs", data: projects });

});

});

查看:

<table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">CSI ID</th>
<th scope="col">App Name</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<!-- get projects array from the data property -->
<% for (var i = 0; i < data.length; i++) { %>
<tr>
<td><%= data[i].id %></td>
<td><%= data[i].name %></td>
</tr>
<% } %>
</tbody>
</table>

关于javascript - 如何将 JSON 对象传递给 EJS javascript 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48675535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com