【问题标题】:How to know which button was pressed?如何知道按下了哪个按钮?
【发布时间】:2015-11-13 23:04:58
【问题描述】:

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

<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

如何访问按钮的名称?

【问题讨论】:

  • 如果我明白了,那就不是 shire。所以我不能在一种形式中使用两个按钮,然后只阅读上面写的内容?
  • 60% 我赞成这个的原因是因为您将按钮命名为“butt1”和“butt2”。
  • 这里还有console.log(req.body.name),你还没有名称为name的字段。

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


【解决方案1】:

我认为这对你有帮助。

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

【讨论】:

    【解决方案2】:

    首先,由于您使用的是 POST,我假设您已经安装了 body-parser 中间件,如果没有,请检查 Body Parser Middleware

    您的代码需要一些更改

    在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】:

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

      <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,具体取决于单击的按钮。

      【讨论】:

        【解决方案4】:

        我知道这是一个非常古老的问题,但我也有同样的问题,并且我找到了更好的解决方案,所以我想我会分享它。您可以将不同的表单操作添加到不同的按钮,并在您的应用程序中对操作执行不同的操作。示例:

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

        【讨论】:

          猜你喜欢
          • 2022-08-18
          • 1970-01-01
          • 2011-04-11
          • 2021-10-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-09
          相关资源
          最近更新 更多