[英]Submitting a form with multiple submit values
I have a voting webapp I'm building in PHP, and I'm looking for a straightforward solution to this simple problem (quite a fun problem I think!): 我有一个投票的webapp我用PHP构建,我正在寻找一个直接的解决方案来解决这个简单的问题(我认为这是一个非常有趣的问题!):
The voting form requires you to enter your email address to vote. 投票表格要求您输入您的电子邮件地址进行投票。 I need each vote option to be a submit button.
我需要每个投票选项都是一个提交按钮。
In pseudo HTML it would look like this: 在伪HTML中,它看起来像这样:
<form>
<input type=email>
<input type=submit name=voteOption1 value=VOTE>
<input type=submit name=voteOption2 value=VOTE>
<input type=submit name=voteOption3 value=VOTE>
</form>
This works fine except for one thing: You will have noticed that the value
for each of the submit buttons is VOTE - this cannot be changed . 这样可以正常工作,除了一件事:您会注意到每个提交按钮的
value
都是VOTE - 这是无法更改的 。 So I get the following from the server: 所以我从服务器获得以下内容:
[email] => hello@example.com
[voteOption1] => VOTE
I need to know which option they voted for (eg. voteOption1
). 我需要知道他们投票的选项(例如,
voteOption1
)。 Yes, the HTML can be changed. 是的,HTML可以更改。
How would you solve this? 你怎么解决这个问题?
Use an HTML 4 submit button instead of an HTML 3.2 one. 使用HTML 4提交按钮而不是HTML 3.2提示按钮。 Then you can have a different value and display text.
然后,您可以拥有不同的值并显示文本。
<button name="vote" value="Option 1">
VOTE
</button>
Thanks for the answers. 谢谢你的回答。 Another way to solve this is to send a form array.
解决此问题的另一种方法是发送表单数组。 For example:
例如:
<form>
<input type=email>
<input type=hidden name=voteOption1[option] value=voteOption1>
<input type=submit name=voteOption1[submit] value=VOTE>
<input type=hidden name=voteOption2[option] value=voteOption2>
<input type=submit name=voteOption2[submit] value=VOTE>
<input type=hidden name=voteOption3[option] value=voteOption3>
<input type=submit name=voteOption3[submit] value=VOTE>
</form>
So I get the following from the server: 所以我从服务器获得以下内容:
[email] => hello@example.com
[voteOption1] => Array
(
[option] => voteOption1
[submit] => VOTE
)
[voteOption2] => Array
(
[option] => voteOption2
)
[voteOption3] => Array
(
[option] => voteOption3
)
Then you can simply look for the submit: 然后你可以简单地寻找提交:
foreach ($submittedForm as $data) {
if (array_key_exists ('submit', $data)) {
$request->option = $data['option'];
break;
}
}
The downside to this is that all elements are submitted, but in this instance that's not a problem. 这样做的缺点是所有元素都已提交,但在这种情况下,这不是问题。
Am I getting it wrong or do you actually need to check which submit button is clicked? 我是弄错了还是你真的需要检查点击了哪个提交按钮?
if (isset($_POST['voteOption1']) {
// VoteOption1 Clicked
} elseif (isset($_POST['voteOption2']) {
// VoteOption2 Clicked
} elseif (isset($_POST['voteOption3']) {
// VoteOption3 Clicked
}
<input type=submit name=voteOption1 value=VOTE1>
<input type=submit name=voteOption2 value=VOTE2>
etc..? 等等..?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.