【问题标题】:HTML Element Array, name="something[]" or name="something"?HTML 元素数组,name="something[]" 还是 name="something"?
【发布时间】:2011-06-09 00:01:36
【问题描述】:

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

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

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

但据我所知,name 已准备好 HTML 输入元素的数组。 在客户端 (GetElementsByName) 或服务器端(PHP 中的 $_POST 或 ASP.NET 中的 Request.Form)。

例如:name="education",那么与 or 有什么不同 没有[]

【问题讨论】:

  • 使用education[],您可以使用名称为education[subject][1] 和education[subject][2] 的输入字段作为在服务器端获取相应的关联数组(在php $_POST['教育'])
  • 链接已损坏:“未找到。在此服务器上找不到请求的 URL /。”

标签: php html


【解决方案1】:

不一样。

如果您发布此表单:

<input type="text" name="education[]" value="1">
<input type="text" name="education[]" value="2">
<input type="text" name="education[]" value="3">

您将在 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">

您将获得最后一个值。在这里你会得到$_POST['education'] = 3

【讨论】:

    【解决方案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>
    

    【讨论】:

      【解决方案3】:

      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>
      

      【讨论】:

      • 但是在我的代码中,当我通过 jquery 访问数组值时,它也会获得一个额外的空输入值。假设我输入了 2 个值,但它带有 3 个值,其中一个值是一个空字符串。
      猜你喜欢
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      相关资源
      最近更新 更多