HTML 元素数组,name=“something[]” 或 name=“something”?

2022-08-30 11:49:38

我在这个网站上看到了一些东西:

处理 JavaScript 和 PHP http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=343 中的 HTML 表单元素数组

它说要将数组放在属性中以及如何获取输入集合的值。例如namename="education[]"

但据我所知,HTML输入元素是数组就绪的。在客户端 () 或服务器端(在 PHP 或 ASP.NET 中)。nameGetElementsByName$_POSTRequest.Form

例如:,那么有或没有?name="education"[]


答案 1

PHP使用方括号语法将表单输入转换为数组,因此当您使用时,当您执行此操作时,您将获得一个数组:name="education[]"

$educationValues = $_POST['education']; // Returns an array
print_r($educationValues); // Shows you all the values in the array

例如:

<p><label>Please enter your most recent education<br>
    <input type="text" name="education[]">
</p>
<p><label>Please enter any previous education<br>
    <input type="text" name="education[]">
</p>
<p><label>Please enter any previous education<br>
    <input type="text" name="education[]">
</p>

将为您提供数组内所有输入的值。$_POST['education']

在JavaScript中,通过id获取元素更有效率...

document.getElementById("education1");

ID 不必与名称匹配:

<p><label>Please enter your most recent education<br>
   <input type="text" name="education[]" id="education1">
</p>

答案 2

如果有复选框,则可以传递已检查值的数组。

<input type="checkbox" name="fruits[]" value="orange"/>
<input type="checkbox" name="fruits[]" value="apple"/>
<input type="checkbox" name="fruits[]" value="banana"/>

还有多个选择下拉列表

<select name="fruits[]" multiple>
    <option>apple</option>
    <option>orange</option>
    <option>pear</option>
</select>

推荐