最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin15浏览0评论

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

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

所以我正在学习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') %>
回答如下:

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)

  1. 暂无评论