在get表单中为相同的复选框字段传递两个值

时间:2013-09-11 23:51:15

标签: php html forms

我有一张method="get"的表单,现在它看起来像这样:

    <form>
            <input type="submit" id="searchsubmit" value="Sort Projects" class="project-sort" />
            <input type="checkbox" name="type" class="type-checkbox" value="type1"> 
            <label for="type1">Type 1</label>
            <input type="checkbox" name="type" class="type-checkbox" value="type2"> 
            <label for="type1">Type 2</label>
            <input type="checkbox" name="type" class="type-checkbox" value="type3"> 
            <label for="type1">Type 3</label>
    </form>

然而,当我选择其中两个时,它发送给我的网址看起来像这样 /?type=type1&type=type2

我已经尝试在输入名称中添加[ ],当发生这种情况时,网址会显示为:

/?type%5B%5D=type1&type%5B%5D=type2

知道我在这里做错了什么?

3 个答案:

答案 0 :(得分:2)

为每个复选框使用不同的名称(不要为每个复选框使用name =“type”)

<form>
  <input type="submit" id="searchsubmit" value="Sort Projects" class="project-sort" />
  <input type="checkbox" name="type1" class="type-checkbox" value="type1"> 
  <label for="type1">Type 1</label>
  <input type="checkbox" name="type2" class="type-checkbox" value="type2"> 
  <label for="type2">Type 2</label>
  <input type="checkbox" name="type3" class="type-checkbox" value="type3"> 
  <label for="type3">Type 3</label>
</form>

匹配名称用于单选按钮组,而不是复选框。
一般而言,匹配名称用于单选按钮组,而不是复选框。使用匹配名称有一些原因(如下所述),但显然在执行此操作时会涉及到问题。

也许OP可以手动explode or preg_split接收端的整个查询字符串,然后创建一个包含所有“类型”值的数组,(即不要使用$ _GET [“type”])。

答案 1 :(得分:0)

在表单上使用GET操作会将其多次放入查询字符串中。但是当接收页面从查询字符串中获取值时,它会将它们放在一起。

Querystring看起来像:/?type = type1&amp; type = type2

从查询字符串中获取参数“type”的值时,该值将为“type1,type2”

使用经典ASP,从表单集合中获取信息时:

查询字符串:http://domain.com/page.asp?type=type1&type=type2

收集这样的信息:

<%
    response.write("Value of type is: " & request("type"))
%>

输出到页面:

类型的值是:type1,type2

答案 2 :(得分:0)

如果您使用类型[]作为名称,则网址将显示为/?type%5B%5D = type1&amp; type%5B%5D = type2,如您所发现的那样。

这是/?type [] = type1&amp; type [] = type2的urlencoded [1]形式。 ([编码为%5B,]编码为%5b) 使用这种语法,php将使类型为包含值“type1”和“type2”

的数组

一个例子:

<html>
  <head><title>test</title></head>
  <body>
    <pre>$_GET is <?php var_dump($_GET); ?></pre>
    <hr/>
    <form method="get" action="">
      <input type="submit" id="searchsubmit" value="Sort Projects" class="project-sort" />
      <input type="checkbox" name="type[]" class="type-checkbox" value="type1"> 
      <label for="type1">Type 1</label>
      <input type="checkbox" name="type[]" class="type-checkbox" value="type2"> 
      <label for="type1">Type 2</label>
      <input type="checkbox" name="type[]" class="type-checkbox" value="type3"> 
      <label for="type1">Type 3</label>
    </form>
  </body>
</html>

试试这个,你会看到你得到的价值观的结构。 例如,如果您检查第一个和第三个框,则表单上方的输出将如下所示:

$_GET is array(1) {
  ["type"]=>
  array(2) {
    [0]=>
    string(5) "type1"
    [1]=>
    string(5) "type3"
  }
}

[1] http://en.wikipedia.org/wiki/Percent-encoding