我在表单中有两个提交按钮。我如何确定哪一个被击中服务器端?
一种形式的两个提交按钮
Define name
as array
.
<form action='' method=POST>
(...) some input fields (...)
<input type=submit name=submit[save] value=Save>
<input type=submit name=submit[delete] value=Delete>
</form>
Example server code (PHP):
if (isset($_POST["submit"])) {
$sub = $_POST["submit"];
if (isset($sub["save"])) {
// save something;
} elseif (isset($sub["delete"])) {
// delete something
}
}
elseif
very important, because both will be parsed if not.
Enjoy.
使用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>
更好的解决方案包括使用按钮标签提交表单:
<form>
...
<button type="submit" name="action" value="update">Update</button>
<button type="submit" name="action" value="delete">Delete</button>
</form>
按钮内的HTML (例如..>Update<..
,用户看到的内容;由于提供了HTML,因此value
用户不可见;它仅发送到服务器。这样就不会给国际化和多种显示语言带来麻烦(在在以前的解决方案中,按钮的标签也是发送到服务器的值)。
这非常容易测试
<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
<form>
<input type="submit" value="Submit to a" formaction="/submit/a">
<input type="submit" value="submit to b" formaction="/submit/b">
</form>
该formaction
属性有一种新的HTML5方法:
<button type="submit" formaction="/action_one">First action</button>
<button type="submit" formaction="/action_two">Second action</button>
显然,这在IE9及更早版本中不起作用,但是对于其他浏览器,您应该没问题(请参阅:w3schools.com HTML <button> formaction Attribute)。
Personally, I generally use Javascript to submit forms remotely (for faster perceived feedback) with this approach as backup. Between the two, the only people not covered are IE<9 with Javascript disabled.
Of course, this may be inappropriate if you’re basically taking the same action server-side regardless of which button was pushed, but often if there are two user-side actions available then they will map to two server-side actions as well.
Edit:
As noted by Pascal_dher in the comments, this attribute is also available on the <input>
tag as well.
如果给每个人起一个名字,那么被点击的人将作为其他任何输入被发送出去。
<input type="submit" name="button_1" value="Click me">
Simple you can change the action of form on different submit buttons Click.
Try this in document.Ready