我在一个表单中有两个提交按钮。我如何确定哪一个击中了服务器端?


当前回答

简单。你可以在不同的提交按钮上点击改变表单的动作。

在文档中试试这个。准备好:

$(".acceptOffer").click(function () {
    $("form").attr("action", "/Managers/SubdomainTransactions");
});

$(".declineOffer").click(function () {
    $("form").attr("action", "/Sales/SubdomainTransactions");
});

其他回答

由于您没有指定使用的服务器端脚本方法,因此我将给出一个适用于PHP的示例

<?php if(isset($_POST["loginForm"])) { print_r ($_POST); // FOR Showing POST DATA } elseif(isset($_POST["registrationForm"])) { print_r ($_POST); } elseif(isset($_POST["saveForm"])) { print_r ($_POST); } else{ } ?> <html> <head> </head> <body> <fieldset> <legend>FORM-1 with 2 buttons</legend> <form method="post" > <input type="text" name="loginname" value ="ABC" > <!--Always use type="password" for password --> <input type="text" name="loginpassword" value ="abc123" > <input type="submit" name="loginForm" value="Login"><!--SUBMIT Button 1 --> <input type="submit" name="saveForm" value="Save"> <!--SUBMIT Button 2 --> </form> </fieldset> <fieldset> <legend>FORM-2 with 1 button</legend> <form method="post" > <input type="text" name="registrationname" value ="XYZ" > <!--Always use type="password" for password --> <input type="text" name="registrationpassword" value ="xyz123" > <input type="submit" name="registrationForm" value="Register"> <!--SUBMIT Button 3 --> </form> </fieldset> </body> </html>

形式

当点击Login -> loginForm

当点击Save -> saveForm

当点击注册->注册表单

使用formaction HTML属性(第5行):

<form action="/action_page.php" method="get">
    First name: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>
    <button type="submit">Submit</button><br>
    <button type="submit" formaction="/action_page2.php">Submit to another page</button>
</form>

也许这里建议的解决方案在2009年是有效的,但我已经测试了所有这些被好评的答案,没有一个在任何浏览器上都有效。

我发现唯一有效的解决方案是这样的(但我觉得用起来有点难看):

<form method="post" name="form">
    <input type="submit" value="dosomething" onclick="javascript: form.action='actionurl1';"/>
    <input type="submit" value="dosomethingelse" onclick="javascript: form.action='actionurl2';"/>
</form>

这非常容易测试:

<form action="" method="get">
    <input type="submit" name="sb" value="One">
    <input type="submit" name="sb" value="Two">
    <input type="submit" name="sb" value="Three">
</form>

只需将其放入HTML页面,单击按钮,然后查看URL。

你也可以这样做(我认为如果你有N个输入,这很方便)。

<input type="submit" name="row[456]" value="something">
<input type="submit" name="row[123]" value="something">
<input type="submit" name="row[789]" value="something">

一个常见的用例是为每个按钮使用来自数据库的不同id,这样稍后您就可以知道在服务器中单击了哪一行。

在服务器端(本例为PHP),您可以将“row”读取为数组以获取id。

$_POST['row']将是一个只有一个元素的数组,形式为[id => value](例如:[' 123' => 'something'])。

所以,为了得到点击的id,你做:

$index = key($_POST['row']);

key