2014-01-07 26 views
3

我使用Node + JS + Express + Jade將網頁值插入到Mongo DB中。 我需要插入True或False,取決於複選框是否啓用。閱讀複選框的值Node + JS + Express + Jade

在我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

當複選框被選中時,瀏覽器將複選框的值添加到請求中。有幾種方法可以處理服務器上的這種行爲。

最明顯的是將參數的缺失視爲錯誤。

另一種方式是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 Active input(type="checkbox", name="checkedboxes[]",checked='true')

這會給你的檢查框的陣列req.body