显示级联下拉列表

时间:2014-12-03 08:27:18

标签: php jquery mysql sql mysqli

的index.php

<div id="container">
  <div id="body">
    <div id="dropdowns">
       <div id="center" class="cascade">
          <?php
        $sql = "SELECT searchname FROM search_parent";
        $query = mysqli_query($con, $sql);
        ?>
            <label>First Option:
            <select name="searchname" id = "drop1">
              <option value="">Please Select</option>
              <?php while ($rs = mysqli_fetch_array($query, MYSQLI_ASSOC )) { ?>
              <option value="<?php echo $rs["id"]; ?>"><?php echo $rs["searchname"]; ?></option>
              <?php } ?>
            </select>
            </label>
          </div>

        <div class="cascade" id="state"></div> 

          <div id="city" class="cascade"></div> 
        </div>
    </div>
  </div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("select#drop1").change(function(){

    var country_id =  $("select#drop1 option:selected").attr('value'); 
// alert(country_id);   
    $("#state").html( "" );
    $("#city").html( "" );
    if (country_id.length > 0 ) { 

     $.ajax({
            type: "POST",
            url: "fetch_state.php",
            data: "country_id="+country_id,
            cache: false,
            beforeSend: function () { 
                $('#state').html('<img src="loader.gif" alt="" width="24" height="24">');
            },
            success: function(html) {    
                $("#state").html( html );
            }
        });
    } 
});
});
</script>

fetch_state.php

<?php

include("connection.php");
$country_id = trim(mysqli_escape_string($con,$_POST["country_id"]));

$sql = "SELECT * FROM t1 WHERE parent_id = '".$country_id ."' ";
$count = mysqli_num_rows( mysqli_query($con, $sql) );
if ($count > 0 ) {
$query = mysqli_query($con, $sql);
?>
<label>Select: 
<select name="state" id="drop2">
    <option value="">Please Select</option>
    <?php while ($rs = mysqli_fetch_array($query, MYSQLI_ASSOC)) { ?>
    <option value="<?php echo $rs["id"]; ?>"><?php echo $rs["title"]; ?></option>
    <?php } ?>
</select>
</label>
<?php 
    }

?>

<script src="jquery-1.9.0.min.js"></script>

search_parent的表格

id  searchname
1     t1
2     t2
3     t3

当用户选择t1时,第二个下拉列表中的值应该从t1表中填充,如果选择了t2,它应该从t2表中填充,如果选择t3,则应从t3表填充第二个下拉列表

表t1

id   title   parent_id
1    tt1      1

然而,当我运行此代码时,它不起作用它只显示第一个下拉列表,当我选择一个值时,没有任何内容进一步显示

1 个答案:

答案 0 :(得分:0)

我认为您的问题是,您错过了id字段。

因此,在您的第一个查询中,您说:

SELECT searchname FROM search_parent

如您所述,可能是t1t2t3。 但是您没有在查询中选择id字段,但您已尝试将其添加为选项值:

<option value="<?php echo $rs["id"]; ?>"><?php echo $rs["searchname"]; ?></option>
                       here^^^^^^^^^

所以价值中没有任何东西。

您需要将查询更改为

SELECT id,searchname FROM search_parent