[英]Print data from mongodb to ejs using nodeJS
我有這種JSON數據。 該數據是從MongoDB獲取的。 我想在EJS頁面上打印。
[{_id:59157619e9bcd218d9dd4dba,例如:“您對該產品的總體滿意度如何?”,鍵入:“收音機”,選項:[“一點都不滿意”,“滿意”,“非常滿意”]}]
選項將是單選按鈕。
假設您有這樣的api。
app.get('/testing', function (req, res) {
var array = [{
_id: '59157619e9bcd218d9dd4dba',
que: 'Overall how satisfied are you with the product?',
type: 'radio',
options: ['Not at all satisfied', 'satisfied', 'Very much satisfied ']
}]
res.render('load', array);
//load is the ejs file (load.ejs) and array is the array of object.
});
假設這是您的ejs文件,並且您想將此數組發送到ejs文件中,例如...
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
table, td, th {
padding: 8px;
border: 1px solid #ddd;
text-align: left;
}
</style>
</head>
<body>
<h2><%= HeadLine %></h2>
<table>
<tr style='background-color: gainsboro;'>
<th>Id</th>
<th>question</th>
<th>type</th>
<th>options</th>
</tr>
<% array.forEach(function(data) { %>
<tr>
<td >
<p><%= data.seq %></p>
</td >
<td>
<p><%= data.id %></p>
</td>
<td >
<p> <%= data.question %></p>
</td >
<td >
<p><%= data.type %></p>
</td >
<td >
<p> <%= data.options %></p>
</td >
</tr>
<% }); %>
</table>
</body>
</html>
您需要將json數據從路由器文件傳遞到ejs文件,這可能會有所幫助-router.js
router.get('/radio', function(req, res) {
var data = [ { _id: 59157619e9bcd218d9dd4dba, que: 'Overall how satisfied are you with the product?', type: 'radio', options: [ 'Not at all satisfied', 'satisfied', 'Very much satisfied ' ] } ]; //replace this with the service getting data
res.render('radio/show', data);
})
ejs文件-radio.js
<form>
<input type="radio" checked><%= data.options[0] %><br>
<input type="radio"><%= data.options[1] %><br>
<input type="radio"><%= data.options[2] %><br>
</form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.