逗号分隔复选框$ _GET查询请求与jquery

时间:2014-02-07 02:02:45

标签: php jquery

尝试使用多个复选框创建搜索功能,但似乎只查找与$ _POST请求相关的信息。

<input type="checkbox" name="fruit" value="1">
<input type="checkbox" name="fruit" value="2">
<input type="checkbox" name="fruit" value="3">
<input type="checkbox" name="fruit" value="4">
<input type="checkbox" name="fruit" value="5">

使查询看起来像这样的最佳方法是什么

search?fruit=1,2,3,4

有没有办法做这个非ajax?

只是为了澄清......

每个值代表不同的水果。

最初我做了这个

 

search?apple=1&orange=1

当我添加更多复选框时,查询似乎效率低下。

我知道我可以使用$ _POST方法将复选框添加到数组中

<input type="checkbox" name="fruit[]" value="1">
<input type="checkbox" name="fruit[]" value="2">

正如一些人建议在$ _GET查询中使用此技术看起来像这样

search?fruit[]=1&fruit[]=2&fruit[]=5

所以问题是如何清理它(逗号分隔)

3 个答案:

答案 0 :(得分:3)

注意:正如其他人所指出的那样,没有必要传递一个带逗号分隔值的参数,最终得到服务器上的数组或逗号分隔值。 PHP之类的框架可以在不需要JavaScript的情况下处理这个问题。您可以简单地为每个复选框指定相同的“名称”属性。这将导致多个具有相同名称的参数传递给服务器,这很好。实际上,如果使用<select multiptle="multiple">元素,则会得到相同的结果。

在PHP中,如果在末尾使用带方括号的名称,例如fruit[],则可以在服务器上获取一个数组:

$_GET['fruit']

如果您想在服务器上使用逗号分隔值,则可以使用:

implode(',', $_GET['fruit'])

但是如果您真的想要一个带逗号分隔值的参数,请按以下步骤操作:

您可以使用带有隐藏输入的表单。将表单的“方法”设置为"get",将隐藏输入的“名称”设置为"fruit"。然后添加一个事件处理程序,在提交表单时将隐藏输入的值设置为以逗号分隔的字符串。

HTML:

<form id="fruitForm" action="search" method="get">
<input type="hidden" name="fruit" />
<label><input type="checkbox" value="1" />apple</label><br />
<label><input type="checkbox" value="2" />banana</label><br />
<label><input type="checkbox" value="3" />orange</label><br />
<label><input type="checkbox" value="4" />pineapple</label><br />
<label><input type="checkbox" value="5" />grapefruit</label><br />
<button type="submit">submit</button>
</form>

JQuery的:

$('#fruitForm').submit(function() {
    var fruits = $('#fruitForm').find('input:checkbox:checked').map(function() {
        return $(this).val();
    }).get().join(',');

    $('#fruitForm').find('input[name=fruit]').val(fruits);
});

注意:复选框元素没有“name”属性,因此它们不会包含在表单提交中。

jsfiddle

答案 1 :(得分:1)

使用fruit[]作为输入名称

<input type="checkbox" name="fruit[]" value="1">
<input type="checkbox" name="fruit[]" value="2">
<input type="checkbox" name="fruit[]" value="3">
<input type="checkbox" name="fruit[]" value="4">
<input type="checkbox" name="fruit[]" value="5">

您将获得以下内容:

echo "<pre>", print_r($_GET["fruit"], true);

输出

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

答案 2 :(得分:0)

试试这个,使用checkbox名称fruit[]。在php中获取fruit数组并使用implode()

转换为字符串
    <?php
       echo $fruits = implode(",",$_GET['fruit']); //1,2,3,4,5
    ?>
    <form>
    <input type="checkbox" name="fruit[]" value="1">
    <input type="checkbox" name="fruit[]" value="2">
    <input type="checkbox" name="fruit[]" value="3">
    <input type="checkbox" name="fruit[]" value="4">
    <input type="checkbox" name="fruit[]" value="5">        
    <input type="submit">
   </form>
相关问题