如何在单个 HTML 表单中提交多个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43267778/
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
How to Submit Multiple Values in a single HTML Form?
提问by Jase
So I have a HTML form:
所以我有一个 HTML 表单:
<html>
<body>
<script>history.pushState('', '', '/')</script>
<form action="http://myserver.com" method="POST">
<input type="hidden" name="Id" value="83" />
<input type="hidden" name="url" value="http://example.com/" />
<input type="submit" value="Submit request" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
As you can see this is submitting the action for <input type="hidden" name="Id" value="83" />
meaning it's submitted for the attribute associated with ID number 83, I'm wanting the action to be submitted for multiple ID values, i.e. 1 - 100. Is this possible? If so how can it be done?
正如您所看到的,这是提交操作,<input type="hidden" name="Id" value="83" />
表示它是为与 ID 号 83 关联的属性提交的,我希望为多个 ID 值(即 1 - 100)提交操作。这可能吗?如果是这样怎么办?
回答by Long Kim
I assume you want to do something like this
我假设你想做这样的事情
<html>
<body>
<script>history.pushState('', '', '/')</script>
<form action="http://myserver.com" method="POST">
<input type="hidden" name="Id[]" value="83" />
<input type="hidden" name="Id[]" value="85" />
<!-- you can add as many as input here for id if you want -->
<input type="hidden" name="url" value="http://example.com/" />
<input type="submit" value="Submit request" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
After this form is posted, on the server side you can get $_POST['id'] as an array and playing around with it.
发布此表单后,在服务器端,您可以将 $_POST['id'] 作为数组获取并使用它。
回答by Leszek P
Add [] to input name:
将 [] 添加到输入名称:
<input type="hidden" name="ID[1]" value="83" />
<input type="hidden" name="ID[100]" value="100" />
then the in php
然后在 php
print_r($_POST['ID']); //print out the data array
Or use just one input with comma separated values?
或者只使用一个带有逗号分隔值的输入?
<input type="hidden" name=Id value="1, 2, 3,.., 100" />
PHP:
PHP:
$ids = explode(" ", $_POST['ID']);
回答by Carlos F
By doing document.forms[0].submit();
you are submitting all the input values in that form and values will be saved as Id=83&url=http://example.com/
通过这样做,document.forms[0].submit();
您将提交该表单中的所有输入值,并且这些值将被保存为Id=83&url=http://example.com/
If you want to submit several forms then you could use a for loop
如果要提交多个表单,则可以使用 for 循环
x = document.forms.length //your desired number or number of forms
for(i = 0; i<x; i++){
document.forms[i].submit();
}