如何填充第二个下拉基础上选择使用jQuery / AJAX和PHP / MySQL的一个下拉的? [英] How to populate second dropdown based on selection of first dropdown using jQuery/AJAX and PHP/MySQL?

查看:158
本文介绍了如何填充第二个下拉基础上选择使用jQuery / AJAX和PHP / MySQL的一个下拉的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一组动态的下拉框,使用jQuery / AJAX和PHP / MySQL的。当基于从数据库值在页面加载的第一个下拉框将被填充。第二个下拉框应显示的基础上,从第一个下拉框中选择一组值。我知道已经有问过就到这里类似的问题,但我还没有找到一个解决方案,符合我的情况。

我的查询,生成一个JSON恩codeD下降是正常的第二个下拉值的列表,但我有问题,将其填充到实际的下拉表单元素。关于我要去哪里错了任何想法。

JavaScript的:

 <脚本>
$()。就绪(函数(){

    $(#例如item_1)。改变(函数(){

      VAR GROUP_ID = $(本).VAL();

       $阿贾克斯({
            键入:POST,
            网址:../../db/groups.php?item_1_id=+ GROUP_ID,
            数据类型:JSON,
            成功:功能(数据){
                //对应一个下拉的早期选择清除选项
                $('#选择item_2')空()。
                $('#选择item_2)追加。('<期权价值=0>选择选项< /选项>');
                //填充第二个下拉选项
                $每个(data.subjects,函数(){
                    $('选择#item_2)追加('<期权价值=+ $(本).attr('GROUP_ID')+'>'+ $(本).attr('名')+ '< /选项>');
                });
                $('#选择item_2)专注()。
            },
            beforeSend:函数(){
                $('#选择item_2')空()。
                $('#选择item_2)追加。('<期权价值=0>载入中...< /选项>');
            },
            错误:函数(){
                $('#选择item_2)ATTR(禁用,真正的)。
                $('#选择item_2')空()。
                $('#选择item_2)追加('<期权价值=0>无选项< /选项>')。
            }
        })

    });
});

< / SCRIPT>
 

HTML:

 <标签ID =item_1_label为=例如item_1类=标签>#1:< /标签>
<选择一个id =例如item_1NAME =例如item_1/>
    <期权价值=>选择< /选项>
    < PHP
        而$ sth = $ dbh->查询(SELECT ID,名称,级别
                             从组中
                             其中level =1
                             按名称集团
                             ORDER BY名);
        而($行= $ sth->取()){
            回声'<期权价值='。$行['身份证'。'>'$行['名称']。'< /选项>'\ N。
        }
     ?>
< /选择>

<标签ID =item_2_label为=item_2类=标签>#2:< /标签>
<选择一个id =item_2NAME =item_2/>
< /选择>
 

PHP:

 < PHP

require_once(../包括/将connect.php);

$ item_1_id = $ _GET ['item_1_id'];

$胸径= get_org_dbh($ org_id);

$ return_arr =阵列();

而$ sth = $ dbh->查询(SELECT ID,名称,级别
                     从组中
                     其中level ='2'
                     和家长= $ item_1_id
                     按名称集团
                     ORDER BY名);

而($行= $ sth->取()){

    $ row_array =阵列(名称=> $行['名称'],
                       ID=> $行['身份证']);

    array_push($ return_arr,$ row_array);
}

回声json_en code($ return_arr);

?>
 

样品JSON输出:

  [{名:A,ID:0},{名:B,ID:1},{ 名:C,ID:2}]
 

解决方案

首先,你的文档就绪看起来有点过,它应该要么是 $(文件)。就绪(函数(){} ); 或者它可能只是 $(函数(){});

二,你遍历JSON结果看起来有点古怪,以及。尝试像这样:

  $。每个(data.subjects,功能(我,VAL){
   $('#选择item_2)追加。('<期权价值=+ val.id +'>+ val.name +'< /选项>');
});
 

I am trying to create a dynamic set of dropdown boxes, using jQuery/AJAX and PHP/MySQL. The first dropdown box will be populated when the page loads based on values from a database. The second dropdown box should display a set of values based on the selection from the first dropdown box. I know there have been similar questions asked on here before, but I haven't found a solution that matches my scenario.

My query to generate a JSON encoded list of values for the second drop down is functioning, but I am having issues populating it into the actual dropdown form element. Any ideas on where I'm going wrong.

Javascript:

<script>
$().ready(function() {

    $("#item_1").change(function () {   

      var group_id = $(this).val();

       $.ajax({
            type: "POST", 
            url: "../../db/groups.php?item_1_id=" + group_id, 
            dataType: "json",
            success: function(data){
                //Clear options corresponding to earlier option of first dropdown
                $('select#item_2').empty(); 
                $('select#item_2').append('<option value="0">Select Option</option>');
                //Populate options of the second dropdown
                $.each( data.subjects, function(){    
                    $('select#item_2').append('<option value="'+$(this).attr('group_id')+'">'+$(this).attr('name')+'</option>');
                });
                $('select#item_2').focus();
            },
            beforeSend: function(){
                $('select#item_2').empty();
                $('select#item_2').append('<option value="0">Loading...</option>');
            },
            error: function(){
                $('select#item_2').attr('disabled', true);
                $('select#item_2').empty();
                $('select#item_2').append('<option value="0">No Options</option>');
            }
        })  

    }); 
});

</script>

HTML:

<label id="item_1_label" for="item_1" class="label">#1:</label>
<select id="item_1" name="item_1" />
    <option value="">Select</option>
    <?php
        $sth = $dbh->query ("SELECT id, name, level 
                             FROM groups
                             WHERE level = '1'
                             GROUP by name
                             ORDER BY name");                                   
        while ($row = $sth->fetch ()) { 
            echo '<option value="'.$row['id'].'">'.$row['name'].'</option>'."\n";       
        }
     ?>
</select>

<label id="item_2_label" for="item_2" class="label">#2:</label>
<select id="item_2" name="item_2" />                        
</select>

PHP:

<?php

require_once('../includes/connect.php');        

$item_1_id = $_GET['item_1_id'];

$dbh = get_org_dbh($org_id);

$return_arr = array();

$sth = $dbh->query ("SELECT id, name, level 
                     FROM groups
                     WHERE level = '2'
                     AND parent = $item_1_id
                     GROUP by name
                     ORDER BY name");   

while ($row = $sth->fetch ()) { 

    $row_array = array("name" => $row['name'], 
                       "id" => $row['id']); 

    array_push($return_arr,$row_array);     
}

echo json_encode($return_arr);

?>  

Sample JSON Output:

[{"name":"A","id":"0"},{"name":"B","id":"1"},{"name":"C","id":"2"}]

解决方案

First, your document-ready looks a bit off, it should either be $(document).ready(function(){}); or it could be just $(function(){});.

Second, you looping over the JSON result looks a bit odd as well. Try something like this instead:

$.each(data.subjects, function(i, val){    
   $('select#item_2').append('<option value="' + val.id + '">' + val.name + '</option>');
});

这篇关于如何填充第二个下拉基础上选择使用jQuery / AJAX和PHP / MySQL的一个下拉的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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