从下拉列表中获取显示表nodejs的值

问题描述 投票:2回答:2

所以我正在学习nodejs和mongodb。我在后端使用expressjs和mongojs,在我的应用程序的前端使用ejs。我想要做的是用户将从下拉列表中选择查看可用类的列表,类列表将显示在表中。例如,如果用户选择all,则数据库中的所有类都将显示在表中。我不知道如何从下拉菜单中获取值并以表格形式显示来自mongodb的数据。这是我到目前为止,我收到此错误:错误:发送后无法设置标头。

admin.js

router.get('/showclass', function(req, res) {
   res.render('showclass');
});
router.post('/showclass', function(req, res) {
    var selectValue = req.body.table;
    if(selectValue == 'all') {
         console.log('All is selected');
         db.classes.find().forEach(function(err, doc) {
            if(err) {
            res.send(err);
            } else {
                res.send(doc);
                res.render('showclass');
            }
        });
    }
});

EJS

<%- include('includes/header') %>
<%- include('includes/navbar') %>

<form method="post" action="/admin/showclass">
<table class="table table-bordered">
  <label>Show Table By:</label>
  <select>
    <option value="all">All</option>
    <option value="recent">Recent</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select>
  <tr>
      <th>Class Name</th>
      <th>Class Time</th>
      <th>Duration</th>
      <th>Instructor</th>
      <th>Maximum Students</th>
      <th>Brief Description</th>
      <th></th>
  </tr>
  <tr>
      <td>Data</td> 
      <td>Data</td>
      <td>Data</td>
      <td>Data</td>
      <td>Data</td>
      <td>Data</td>
      <td><a href="editclass">Edit</a>/Delete</td>
  </tr>
<button type="submit" class="btn btn-default">Submit</button>
</table>
</form>

<%- include('includes/footer') %>
javascript node.js mongodb
2个回答
1
投票

res.sendres.render都做同样的事情,他们发回回用户,你不能同时使用它们,删除res.send(doc)并将你的数据传递给render方法。

router.get('/showclass', function(req, res) {
   res.render('showclass');
});
router.post('/showclass', function(req, res) {
    var selectValue = req.body.table;
    if(selectValue == 'all') {
         console.log('All is selected');
         db.classes.find().forEach(function(err, doc) {
            if(err) {
                res.send(err);
            } else {
                res.render('showclass', { doc: doc });
            }
        });
    }
});

看看express docs


0
投票

您不能同时调用res.sendres.render

您可以在第二个参数中将上下文传递给render函数:

res.render('showclass', doc);

参考:http://expressjs.com/en/guide/using-template-engines.html

© www.soinside.com 2019 - 2024. All rights reserved.