Html 如果 <form> 中的 action 字段有参数会发生什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/732371/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:35:26  来源:igfitidea点击:

What happens if the action field in a <form> has parameters?

htmlformsquery-string

提问by Brandon Yarbrough

Is there a well-supported, common behavior that I can expect if I do something like this in HTML:

如果我在 HTML 中做这样的事情,是否有我可以期待的得到充分支持的常见行为:

<form method="get" action="/somePage.html?param1=foo&param2=foo">
  <input name="param2"></input>
  <input name="param3"></input>
</form>

Seems like this sort of thing is inherently ridiculous, but I've seen it used here and there and I was wondering what on Earth the expected behavior should be. Are browsers smart enough to tack on "&param2=whatever&param3=whatever" to the action, or do they just throw in a second question mark? Or what? Are there cases where this is actually the right way to do things?

看起来这种事情本质上是荒谬的,但我已经看到它在这里和那里被使用,我想知道预期的行为到底应该是什么。浏览器是否足够聪明,可以将“¶m2=whatever¶m3=whatever”添加到操作中,还是只是抛出第二个问号?或者是什么?在某些情况下,这实际上是正确的做事方式吗?

回答by Rex M

If the method attribute is set to GET, the browser drops the querystring parameters from the action attribute before constructing the form argument values.

如果方法属性设置为 GET,浏览器会在构造表单参数值之前从操作属性中删除查询字符串参数。

So in your example, the request to the server on submit will look like: /somePage.html?param2=value&param3=value

因此,在您的示例中,提交时对服务器的请求将如下所示: /somePage.html?param2=value&param3=value

So no, when the method is "GET", as in your example, there's no reason to do this.

所以不,当方法是“GET”时,就像在你的例子中一样,没有理由这样做。

回答by Luke

Not sure, but I think it's better practice to place those variables in hidden input fields. This way it doesn't matter if your posting method is either POST or GET.

不确定,但我认为将这些变量放在隐藏的输入字段中是更好的做法。这样,您的发布方法是 POST 还是 GET 都没有关系。

<form method="get" action="/somePage.html">
  <input name="param2"></input>
  <input name="param3"></input>
  <input type="hidden" name="param1" value="foo" />
  <input type="hidden" name="param2" value="foo" />
</form>

回答by Guffa

You could change the method attribute in the form to "POST" with script before posting the form, so there could be a use for the query string in the action. It hardly seems to be the best solution for anything, though.

您可以在发布表单之前使用脚本将表单中的方法属性更改为“POST”,因此可以在操作中使用查询字符串。不过,它似乎几乎不是任何事情的最佳解决方案。

回答by Mark

Well, all the questions have been answered except the last, to which the answer is yes. For POST, it's allowed, but you may well find cases where it doesn't work. I've seen web servers that only allow postdata orquerystring, so it's not dependable.

好吧,除了最后一个问题,所有问题都得到了回答,答案是肯定的。对于POST,这是允许的,但您可能会发现它不起作用的情况。我见过只允许 postdataquerystring 的web 服务器,所以它不可靠。