如何确定哪个按钮被按下?

7

我正在学习 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

我该如何访问按钮的名称?


你对此有何看法?http://stackoverflow.com/questions/28455284/how-to-know-which-submit-button-was-pressed-in-node-js - Isabek Tashiev
不确定我是否理解了。所以我不能在一个表单中使用两个按钮,只是读取它们上面写的内容吗? - wiwo
3
我点赞的60%原因是你把按钮命名为“butt1”和“butt2”。 - Cole Bittel
同时在这里 console.log(req.body.name),你没有名为name的字段。 - Isabek Tashiev
5个回答

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

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>

在 Express 中

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

req.body.name 需要改为 req.body.butt

/ 需要改为 /home2


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,具体取决于哪个按钮被点击。

0
<form action="/home2" method="post">
   <input type="submit" name="buttons" value="butt1">
   <input type="submit" name="buttons" value="butt2">
</form>

尝试这个,然后根据您的设计应用CSS。

app.post("/home2",async(req,res)=>{
 const selected=req.body.buttons;
 console.log(selected);
})

现在无论你点击哪个按钮,它都可以正常运行。


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

});

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