为什么 html 复选框只传输“on”值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4260918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do html checkboxes only transmit an 'on' value?
提问by Google
I'm just starting to learn internet programming.
我刚刚开始学习互联网编程。
After playing around with checkboxes, I found out the hard way, that it is only when the checkbox is checked that it transmits an 'on' value.
在玩了复选框之后,我发现了一个艰难的方法,只有当复选框被选中时,它才会传输一个“on”值。
Why not also send an 'off' value?
为什么不也发送一个“关闭”值?
采纳答案by Alex C
I think it must be for brevity of transmission. Each request to the server is sent 'over the wire' if you've got a page with thousands of checkboxes on it, you will find that the amount of data to tell the server "this box is off" is actually quite sizeable (seeing as how you'd have to send the NAME of each checkbox element - that could add up to megabytes of information - which would slow the entire user experience & internet down).
我认为它必须是为了传输的简洁。如果您的页面上有数千个复选框,那么发送到服务器的每个请求都会“通过网络”发送,您会发现告诉服务器“此框已关闭”的数据量实际上相当大(请参阅就像您必须发送每个复选框元素的名称一样 - 这可能会增加数兆字节的信息 - 这会降低整个用户体验和互联网速度)。
Whereas in fact you knowthat it is off by virtue of it not being sent - so there's no need to send it.
而事实上你知道它是因为它没有被发送而关闭 - 所以没有必要发送它。
回答by Udi
It is possible to have many checkboxes with the same element name:
可以有多个具有相同元素名称的复选框:
<form action="order.php" method="get">
<p>
<label><input type="checkbox" name="toppings" value="olives"/>Olives</label>
<label><input type="checkbox" name="toppings" value="mushrooms"/>Mushrooms</label>
<label><input type="checkbox" name="toppings" value="onions"/>Onions</label>
<label><input type="checkbox" name="toppings" value="eggplant"/>Eggplant</label>
etc...
</p>
<p><input type="submit" value="Submit"/></p>
</form>
The url will later include only the checked values and will look something like:
该 url 稍后将仅包含选中的值,并且看起来像:
order.php?toppings=mushrooms&toppings=onions&toppings=eggplant
This would have not worked well if an "off" value was sent as well.
如果还发送了“关闭”值,这将不会很好地工作。
回答by Brad Christie
As typical to boolean values, it's presumed off. It's simple to check for, however, just depends on your language of choice. Used PHP as a demonstration, you could check:
作为典型的布尔值,它被假定为关闭。但是,检查起来很简单,这取决于您选择的语言。使用PHP作为演示,您可以检查:
$myvar_enabled = (isset($_GET['myvar']) && $_GET['myvar'] == 'on');
回答by Damien
The default state is 'unchecked' (or off as you state it), so there's no need to declare that information.
默认状态为“未选中”(或在您声明时关闭),因此无需声明该信息。