如何知道按下了哪个按钮?

时间:2015-11-13 23:04:58

标签: javascript node.js button express body-parser

我正在学习node.js和表达框架的基础知识。 我有一个带有两个按钮的简单页面:

<form action="/home2" method="post">
    <button name="butt1">butt1</button>
    <button name="butt2">butt2</button>
</form>

我想在控制台中看到按下了哪个按钮:

router.post('/', function(req, res, next) {
    console.log(req.body.name);
    res.render('home2', { title: 'post' });
});

在控制台中,我看到

undefined

如何访问按钮的名称?

4 个答案:

答案 0 :(得分:2)

我认为这会对你有所帮助。

<form action="/home2" method="post">
   <button name="butt1">butt1</button>
   <button name="butt2">butt2</button>
</form>


router.post('/home2', function(req, res, next) {

  if(req.body.hasOwnProperty("butt1")){
     console.log("butt1 clicked");
  }else{
     console.log("butt2 clicked");
  }
  res.render('home2', { title: 'post' });
});

答案 1 :(得分:1)

您可以使用的一个技巧是将两个用作提交按钮:

<form action="/home2" method="post">
    <button name="button_id" value="1" type="submit">butt1</button>
    <button name="button_id" value="2" type="submit">butt2</button>
</form>

在服务器端,您现在应该将button_id的值设置为1或2,具体取决于单击的按钮。

答案 2 :(得分:1)

首先,因为你使用POST我假设你已经有了身体解析器中间件,如果没有检查Body Parser Middleware

您的代码需要进行一些更改

in html

<form action="/home2" method="post">
    <button name="butt" value='1'>butt1</button>
    <button name="butt" value='2'>butt2</button>
</form>

并在快递中

router.post('/home2', function(req, res, next) {
    console.log(req.body.butt);
    res.render('home2', { title: 'post' });
});

req.body.name必须为req.body.butt

/必须为/home2

答案 3 :(得分:0)

我知道这是一个非常老的问题,但是我有一个相同的问题,并且我找到了一种更好的解决方案,因此我想与大家分享。您可以将不同的formaction添加到不同的按钮,并对应用程序中的操作执行不同的操作。示例:

<form action="/home2" method="post">
    <button formaction="wigglebutt" name="butt" value='1'>butt1</button>
    <button formaction="slapbutt" name="butt" value='2'>butt2</button>
</form>

然后在后端:

app.post("/wigglebutt", (req, res) => {

});

app.post("/slapbutt", (req, res) => {

});
相关问题