使用JSON传递多个复选框项目到PHP文件并查询数据库 [英] Passing multiple checkbox items to PHP file using JSON and querying a DB

查看:259
本文介绍了使用JSON传递多个复选框项目到PHP文件并查询数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将多个不同值的复选框传递给PHP脚本,该脚本将针对所选的值对我的数据库执行搜索。



HTML形式如下:

 < li>< input type =checkboxclass =keywordsvalue =option1 title =option1/>< / li> 
< li>< input type =checkboxclass =keywordsvalue =option2title =option2/>< / li>
< li>< input type =checkboxclass =keywordsvalue =option3title =option3/>< / li>
< li>< input type =checkboxclass =keywordsvalue =option4title =option4/>< / li>
< li>< input type =submitname =submitclass =search/>< / li>

将此代码传递给我的PHP文件的JavaScript代码是:

 < script type =text / javascript> 
$(document).ready(function(){
$(。search)。click(function()
{
$ .post(parser.php ,
{
关键字:$(。关键字:已检查)val()
},
函数(数据)
{
$。 append(< li class ='arrow'>< a href ='parser.php?id =);每个(data,function()
{
$(div#result + this.id +'>+ this.title +< / a>< / li>);
});

$ jsonContent)。show();

},
json);

});

}
< / script>

在parser.php中,我接着输入关键字,然后搜索数据库:

  $ keywords = mysql_real_escape_string($ _GET [keywords]); 
$ query = mysql_query(SELECT * FROM keyworddb WHERE keywords LIKE'%。$ keywords。%');
$ arr = array();
while($ row = mysql_fetch_array($ query))
{
$ arr [] = array(id=> $ row [id],title=> ; $ row [title]);
}
echo json_encode($ arr);

这是伟大的,它运行通过没有任何错误,除了:



1)在firebug它发送超过所选的复选框值,虽然不是多个复选框。如果选择了多个复选框,它只使用第一个复选框值。



2)尽管它会返回所有条目

任何帮助赞赏。



更新:



制作chanegs建议:

 < form id =findkeywords> 
< ul>
< li>< li>< li>< input type =checkboxclass =keywords []value =option1title =option 1/>< / li>
< li>< input type =checkboxclass =keywords []value =option2title =option 2/>< / li>
< li> keywords []value =option3title =option 3/>< / li>
< li>< input type =checkboxclass =keywords []value =option4 title =option 4/>< / li>
< li>< input type =submitname =submitclass =search/>< / li>
< / ul>
< / form>

Javascript已更改为:

  $(document).ready(function(){
$(。search)。click(function()
{
$ .post (parser.php,
{
关键字:$(form#findkeywords)。serialize()
},
function(data)
{
$ .each(data,function()
{
$(div#result)。append(< li class ='arrow'>< a href = .php?id =+ this.id +'>+ this.title +< / a>< / li>);
});

$(div#jsonContent)。show();

},
json);

});
$ b b});

我没有对php文件做任何额外的更改,因为我只是想确保实际上是发送数据。但在FireBug它似乎没有发送任何东西。

解决方案

使用的问题。 val()你的方式是传递一个数组到数据,这样做,你必须使用JSON库来'stringify'发送到你的PHP。如果使用 .serialize(),就不需要在另一端尝试和解析它,它将有数据模拟常规的序列化表单数据。



就我个人而言,我将复选框组命名为数组,并将复选框序列化为一个表单。



表单:

 < form id =checkboxes> 
< li>< input type =checkboxname =keywords []value =option1title =option1/>< / li>
< li>< input type =checkboxname =keywords []value =option2title =option2/>< / li&
< li>< input type =checkboxname =keywords []value =option3title =option3/>< / li>
< li>< input type =checkboxname =keywords []value =option4title =option4/>< / li>
< li>< input type =submitname =submitclass =search/>< / li>
< / form>

JS:

 < script type =text / javascript> 
$(document).ready(function(){
$(。search)。click(function()
{
$ .post(parser.php ,$(form#checkboxes)。serialize(),
function(data)
{
$ .each(data,function()
{
(div#result)。append(< li class ='arrow'>< a href ='parser.php?id =+ this.id +'>+ this.title + < / a>< / li>);
});
$(div#jsonContent)。show();
});
} ;
});
< / script>

然后您需要处理 $ _ POST ['keywords' code>作为数组



您可以使用简单的

  foreach($ _ POST ['keywords'] as $ keyword){
echo $ keyword;
}


I'm trying to pass multiple checkboxes with different values to a PHP script that will run a search against my database for the values that are selected.

The HTML form is as follows:

                <li><input type="checkbox" class="keywords"  value="option1" title="option1" /></li>
                <li><input type="checkbox" class="keywords"  value="option2" title="option2" /></li>
                <li><input type="checkbox" class="keywords"  value="option3" title="option3" /></li>
                <li><input type="checkbox" class="keywords"  value="option4" title="option4" /></li>
                <li><input type="submit" name="submit" class="search" /></li>

The javascript code to pass this to my PHP file is:

        <script type="text/javascript">
    $(document).ready(function(){
        $(".search").click(function()
        {           
        $.post("parser.php", 
                    { 
                        keywords: $(".keywords:checked").val() 
                    }, 
                   function(data)
                   {        
                        $.each(data, function()
                        {   
                            $("div#result").append("<li class='arrow'><a href='parser.php?id=" + this.id + "'>" + this.title + "</a></li>");
                        });

                        $("div#jsonContent").show();

                    }, 
            "json");

        });

    });
    </script>

In parser.php I then take the incoming keyword, and search the database:

$keywords = mysql_real_escape_string ($_GET["keywords"]);
$query = mysql_query("SELECT * FROM keyworddb WHERE keywords LIKE '%". $keywords ."%' ");
$arr = array();
while( $row = mysql_fetch_array ( $query ) )
{
$arr[] = array( "id" => $row["id"], "title" => $row["title"] );
}
echo json_encode($arr);

This is all great, it runs through without any errors except:

1) In firebug it's sending over the selected checkbox value, though not the multiple checkboxes. It only uses the first checkbox value if multiple checkboxes selected.

2) Despite that it returns all entries to the table :( no matter what is selected.

Any help appreciated.

Update:

I've made the chanegs suggested:

            <form id="findkeywords">
            <ul>
                <li><input type="checkbox" class="keywords[]"  value="option1" title="option 1" /></li>
                <li><input type="checkbox" class="keywords[]"  value="option2" title="option 2" /></li>
                <li><input type="checkbox" class="keywords[]"  value="option3" title="option 3" /></li>
                <li><input type="checkbox" class="keywords[]"  value="option4" title="option 4" /></li>
                <li><input type="submit" name="submit" class="search" /></li>
            </ul>
            </form>

The Javascript has been changed to:

        $(document).ready(function(){
        $(".search").click(function()
        {            
        $.post("parser.php", 
                       { 
                           keywords: $("form#findkeywords").serialize() 
                       }, 
                   function(data)
                   {        
                        $.each(data, function()
                        {    
                            $("div#result").append("<li class='arrow'><a href='parser.php?id=" + this.id + "'>" + this.title + "</a></li>");
                        });

                        $("div#jsonContent").show();

                    }, 
            "json");

        });

    });

I haven't made any additional changes to the php file yet as I just want to make sure this is actually sending the data across. But in FireBug it doesn't appear to be sending anything at all.

解决方案

The problem using .val() the way you are is it is passing an array to the data, to do that you would have to use a JSON library to 'stringify' it to send to your php. If you use .serialize() there would be no need to try and parse it on the other side, it will have the data emulate regular serialized form data.

Personally, I would name your checkbox group as an array, and the just serialize the checkboxes as a form.

Form:

<form id="checkboxes">
    <li><input type="checkbox" name="keywords[]"  value="option1" title="option1" /></li>
    <li><input type="checkbox" name="keywords[]"  value="option2" title="option2" /></li>
    <li><input type="checkbox" name="keywords[]"  value="option3" title="option3" /></li>
    <li><input type="checkbox" name="keywords[]"  value="option4" title="option4" /></li>
    <li><input type="submit" name="submit" class="search" /></li>
</form>

JS:

<script type="text/javascript">
$(document).ready(function(){
    $(".search").click(function()
    {           
        $.post("parser.php", $("form#checkboxes").serialize(), 
        function(data)
        {        
            $.each(data, function()
            {   
                $("div#result").append("<li class='arrow'><a href='parser.php?id=" + this.id + "'>" + this.title + "</a></li>");
            });
            $("div#jsonContent").show();
        });
    });
});
</script>

You will then need to treat $_POST['keywords'] as an Array

You can access them with a simple foreach

foreach($_POST['keywords'] as $keyword) {
    echo $keyword;
}

这篇关于使用JSON传递多个复选框项目到PHP文件并查询数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆