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

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

问题描述

我正在尝试使用 jQuery/AJAX 和 PHP/MySQL 创建一组动态下拉框.当页面基于数据库中的值加载时,将填充第一个下拉框.第二个下拉框应根据第一个下拉框中的选择显示一组值.我知道这里之前也有人问过类似的问题,但我还没有找到适合我的方案的解决方案.

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.

我为第二个下拉列表生成 JSON 编码的值列表的查询正在运行,但我在将其填充到实际下拉表单元素中时遇到了问题.关于我哪里出错的任何想法.

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:

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);

?>  

示例 JSON 输出:

Sample JSON Output:

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

推荐答案

首先,你的文档就绪看起来有点不对劲,它应该是 $(document).ready(function(){}); 或者它可能只是 $(function(){});.

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

其次,您对 JSON 结果的循环看起来也有点奇怪.试试这样的:

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天全站免登陆