考虑 HTML5 文档中的以下形式:
<form method="post" action="http://example.com/submit/">
<button name="confirm" value="1" type="submit">Confirm</button>
<button name="re-send" value="1" type="submit">Re-send code</button>
<button name="cancel" value="1" type="submit">Cancel change</button>
</form>
使用 Chrome,点击第一个按钮会产生 confirm=1
的请求负载。类似地,第二个按钮导致 re-send=1
,第三个按钮导致 cancel=1
。
检查服务器端的请求有效负载使我能够确定三个按钮中的哪一个被点击(假设三个键中只有一个出现在请求有效负载中)。
在所有情况下,未单击按钮的键值对都从请求负载中排除。这非常有用。
这种行为(非点击按钮键:值对被排除在请求负载之外)是标准的吗?
最佳答案
据我所知,是的。
来自 HTML4 规范: http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#h-17.13.2
Every successful control has its control name paired with its current value as part of the submitted form data set. ... If a form contains more than one submit button, only the activated submit button is successful.
来自 HTML5 规范: http://www.w3.org/TR/2012/CR-html5-20121217/forms.html#the-button-element
Note: A button (and its value) is only included in the form submission if the button itself was used to initiate the form submission.
我很确定 < IE8 将提交元素内容而不是值(例如 confirm=Confirm),但大多数其他常见浏览器应该可以正常工作。
或许可以考虑:
<form method="post" action="http://example.com/submit/">
<button name="submit-action" value="confirm" type="submit">Confirm</button>
<button name="submit-action" value="re-send code" type="submit">Re-send code</button>
<button name="submit-action" value="cancel change" type="submit">Cancel change</button>
</form>
此外,值得注意的是,一些较旧的浏览器可能有一些场景,它们可能会将其视为没有单击任何按钮(例如,由 javascript 提交的表单或改为输入按钮)。可能值得通过默认“确认”来满足这一点。不过,现代浏览器上的 HTML5 应该不会让您感到难过。
关于HTML 表单,多个提交按钮,post payload 忽略未点击的按钮 : Is this standard behaviour?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16561207/