问题描述
我没有看到隐藏输入的好处?如果您设置隐藏输入的值,为什么不在引用此隐藏输入的位置使用该值?
I don't see the benefit of having hidden input? If you set the value of the hidden input why not just use that value at the point where you reference this hidden input?
这是有原因的,但我只是不知道.
There are reasons for this but I just don't know them.
推荐答案
它们用于传递提交表单时需要的数据.一种更常见的情况是允许用户编辑某些现有条目的表单.您需要知道他们正在编辑哪个条目,以便在他们提交表单时更新数据库中的正确行.用户不需要编辑(甚至不知道)条目的 ID,因此隐藏字段在这里很有效.
They're used to pass data that will be needed when the form is submitted. One of the more common cases would be a form allowing users to edit some existing entry. You'll need to know which entry they're editing so that you can update the correct row in the database when they submit the form. The user doesn't need to edit (or even know) the ID of the entry though, so a hidden field works well here.
网址参数:这也可以通过将参数构建到表单提交到的 url 中来完成:
URL parameters:This could also be done by building the parameters into the url that the form is being submitted to:
<form action="save.php?entry_id=1234">
但这意味着您必须正确处理构建 URL 并自己转义数据,并且服务器接受的 URL 长度是有限的,因此它可能不适用于更长的数据.所以通常使用隐藏的表单字段是更简单的方法.
but this means you have to handle building the URL properly and escaping the data yourself, and the length of URLs servers will accept is limited so it may not work for longer data. So generally using hidden form fields is the easier way to go.
会话变量:当编辑页面加载时,您将条目 ID 存储在会话变量中,然后在保存更改的页面上检索它.不过,这更容易搞砸;设置和维护会话可能需要在几个不同的地方添加代码,然后他们的会话可能会在加载和保存之间过期,如果他们打开多个窗口或选项卡,你必须确保它可以工作,并且你必须确保它当他们后退/前进时不会做奇怪的事情.由于所有这些潜在的缺陷,这并不是解决这个问题的好方法——将 id 与提交的数据一起传递要健壮得多.
Session variables: When the edit page loads you'd store the entry ID in a session variable, and then retrieve it on the page that saves the changes. That's a lot easier to mess up though; setting up and maintaining sessions may require adding code in several different places, and then their session could expire in between loading and saving, and you have to make sure it works if they have multiple windows or tabs open, and you have to make sure it doesn't do weird things when they hit back/forward. Because of all these potential pitfalls it isn't a great way to solve this problem--passing the id with the data being submitted is a lot more robust.
Cookies:在许多语言/框架中,会话使用 cookie 进行跟踪,因此它们基本上是相同的解决方案.陷阱与会话变量相同,即使会话由其他方法跟踪.
Cookies: In many languages/frameworks sessions are tracked using cookies, so they're basically the same solution. The pitfalls are the same as for session variables even when sessions are tracked by other methods though.
这篇关于在 HTML 中隐藏输入有什么意义?这有什么常见用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!