读取复选框的值 Node JS + Express + Jade

3

我正在将网页数据插入Mongo DB数据库,使用的是Node JS + Express + Jade。

我需要根据复选框是否被选中来插入True或False。

在我的router.js文件中,我有以下代码:

app.get('/notification', function(req, res) {
    res.render('notification', {  title: 'Nueva notificacion', notifications : NT });
});

app.post('/notification', function(req, res){
    console.log('Adding new notification');
    AM.addNewNotification({
        name    : req.param('name'),
        notification : req.param('notification'),
        active  : req.param('active')
    }, function(e){
        if (e){
            res.send(e, 400);
        }   else{
            res.send('ok', 200);
        }
    });
});

在我的看法中,我有以下观点:

.controls
                    label#active-me.checkbox Active
                        input(type="checkbox", name="active", id="active",checked='checked')

但是我无法插入它,似乎值没有被接受。 只有名称和通知值(文本)被插入。
{ "name" : "Goodbye world", "notification" : "Short Message Service", "_id" : ObjectId("5298f603bd07b80376000005") }

任何建议吗?
谢谢。
2个回答

2

当复选框被选中时,浏览器会将其值添加到请求中。有几种方法可以处理服务器上的此行为。

最明显的方法是将参数的缺失视为false。

另一种方法是Rails所做的:在复选框之前添加一个名称相同且值为零的隐藏输入。在你的情况下:

.controls
  label#active-me.checkbox Active
  input(type="hidden", name="active", value=0)
  input(type="checkbox", name="active", id="active",checked='checked')

此外,你在app.post中的代码应该使用req.body,而不是req.param

1

.controls label#active-me.checkbox 激活 input(type="checkbox", name="checkedboxes[]",checked='true')

这将在req.body中给您一个选中框的数组


只有在进行多项选择时,它才会返回一个数组。在单个复选框选择时,它仍然返回一个字符串。 - Nikhil Nanjappa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接