读取复选框值Node JS + Express + Jade [英] Read checkbox value Node JS + Express + Jade

查看:138
本文介绍了读取复选框值Node JS + Express + Jade的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node JS + Express + Jade将网页值插入Mongo DB. 并且我需要插入True或False,具体取决于是否启用了复选框.

I'm inserting web page values into a Mongo DB, Im using Node JS + Express + Jade. and I need to insert True or False, depending if checkbox is enabled or not.

在我的 router.js 中,我有以下内容:

In my router.js I have the following:

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);
        }
    });
});

在我看来,我有以下内容:

In my view I have the following:

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

但是我无法插入它,看起来好像没有值. 仅插入名称和通知值(文本).

But I can't insert it, looks like value is not taken. Only name and notification values (Text) are inserted.

{ "name" : "Goodbye world", "notification" : "Short Message Service", "_id" : ObjectId("5298f603bd07b80376000005") }

有什么建议吗?

谢谢

推荐答案

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

Browsers add checkbox's value to requests when the box is checked. There are several ways to handle this behavior on the server.

最明显的是将参数的不存在视为错误.

The most obvious is to treat the absence of parameter as its being false.

Rails的另一种方法是:在复选框之前添加具有相同名称和零值的隐藏输入.就您而言:

Another way is what Rails do: add a hidden input with the same name and zero value before the checkbox. In your case:

.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.

In addition, your code in app.post should probably use req.body, instead of req.param.

这篇关于读取复选框值Node JS + Express + Jade的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆