HTML Element Array,name ="something []"或name ="something"?

Che*_*ung 31 html php

我在这个网站上看到了一些东西: 在JavaScript和PHP中处理HTML表单元素的数组 http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=343

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

但据我所知,HTML输入元素是数组就绪的name.在客户端(GetElementsByName)或服务器端($_POST在PHP或Request.FormASP.NET中),例如:name="education",那么与...有什么不同[]

Fen*_*ton 50

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

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

例如:

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

document.getElementById("education1");
Run Code Online (Sandbox Code Playgroud)

id不必与名称匹配:

<p><label>Please enter your most recent education<br>
   <input type="text" name="education[]" id="education1">
</p>
Run Code Online (Sandbox Code Playgroud)


sis*_*onb 15

如果您有复选框,则可以传递一组已检查的值.

<input type="checkbox" name="fruits[]" value="orange"/>
<input type="checkbox" name="fruits[]" value="apple"/>
<input type="checkbox" name="fruits[]" value="banana"/>
Run Code Online (Sandbox Code Playgroud)

还有多个选择下拉列表

<select name="fruits[]" multiple>
    <option>apple</option>
    <option>orange</option>
    <option>pear</option>
</select>
Run Code Online (Sandbox Code Playgroud)


Gal*_*ley 10

这不一样.如果您发布此表单:

<input type="text" name="education[]" value="1">
<input type="text" name="education[]" value="2">
<input type="text" name="education[]" value="3">
Run Code Online (Sandbox Code Playgroud)

你会得到一个PHP数组,在这个例子中你会得到$_POST['education'] = [1, 2, 3].

如果你发布此表格没有 []:

<input type="text" name="education" value="1">
<input type="text" name="education" value="2">
<input type="text" name="education" value="3">
Run Code Online (Sandbox Code Playgroud)

你会得到最后一个值,在这里你会得到$_POST['education'] = 3.