python小菜 2019-01-26 18:27 采纳率: 0%
浏览 11

php sql依赖下拉列表[关闭]

Closed. This question needs to be more focused. It is not currently accepting answers.
                </div>
            </div>
        </div>
                <hr class="my12 outline-none baw0 bb bc-powder-2">
            <div class="grid fw-nowrap fc-black-600">
                    <div class="grid--cell mr8">
                        <svg aria-hidden="true" class="svg-icon iconLightbulb" width="18" height="18" viewbox="0 0 18 18"><path d="M9.5.5a.5.5 0 0 0-1 0v.25a.5.5 0 0 0 1 0V.5zm5.6 2.1a.5.5 0 0 0-.7-.7l-.25.25a.5.5 0 0 0 .7.7l.25-.25zM1 7.5c0-.28.22-.5.5-.5H2a.5.5 0 0 1 0 1h-.5a.5.5 0 0 1-.5-.5zm14.5 0c0-.28.22-.5.5-.5h.5a.5.5 0 0 1 0 1H16a.5.5 0 0 1-.5-.5zM2.9 1.9c.2-.2.5-.2.7 0l.25.25a.5.5 0 1 1-.7.7L2.9 2.6a.5.5 0 0 1 0-.7z" fill-opacity=".4"></path><path opacity=".4" d="M7 16h4v1a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1v-1z" fill="#3F3F3F"></path><path d="M15 8a6 6 0 0 1-3.5 5.46V14a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1v-.54A6 6 0 1 1 15 8zm-4.15-3.85a.5.5 0 0 0-.7.7l2 2a.5.5 0 0 0 .7-.7l-2-2z" fill="#FFC166"></path></svg>
                    </div>
                <div class="grid--cell lh-md">
                    <p class="mb0">
                        <b>Want to improve this question?</b> Update the question so it focuses on one problem only by <a href="/posts/54381416/edit">editing this post</a>.
                    </p>
                    <p class="mb0 mt6">Closed <span title="2019-01-27 10:49:03Z" class="relativetime">last year</span>.</p>
                </div>
            </div>
    </aside>

I am trying to create a set of dynamic, dependent dropdown lists. I would like two lists to populate when a selection is made in a third list. i.e. When Select1 is chosen, Select2 and Select3 auto-populate simultaneously. I have been muddling around with the PHP and jquery scripts but I have not been successful at modifying the code to do what I want. Any assistance would be greatly appreciated.

ajaxData.php

<?php
//Include the database configuration file
include 'dbConfig.php';

if(!empty($_POST["country_id"])){
    //Fetch all state data
    $query = $db->query("SELECT * FROM states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");

    //Count total number of rows
    $rowCount = $query->num_rows;

    //State option list
    if($rowCount > 0){
        echo '<option value="">Select state</option>';
        while($row = $query->fetch_assoc()){ 
            echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
        }
    }else{
        echo '<option value="">State not available</option>';
    }
}elseif(!empty($_POST["country_id"])){
    //Fetch all city data
    $query = $db->query("SELECT * FROM cities WHERE state_id = ".$_POST['country_id']." AND status = 1 ORDER BY city_name ASC");

    //Count total number of rows
    $rowCount = $query->num_rows;

    //City option list
    if($rowCount > 0){
        echo '<option value="">Select city</option>';
        while($row = $query->fetch_assoc()){ 
            echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
        }
    }else{
        echo '<option value="">City not available</option>';
    }
}
?>

index.php

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Dynamic Dependent Select Boxes by CodexWorld</title>
<meta charset="utf-8">
<style type="text/css">
.container{width: 280px;text-align: center;}
select option{
    font-family: Georgia;
    font-size: 14px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#country').on('change',function(){
        var countryID = $(this).val();
        if(countryID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'country_id='+countryID,
                success:function(html){
                    $('#state').html(html);
                    $('#city').html('<option value="">Select state first</option>'); 
                }
            }); 
        }else{
            $('#state').html('<option value="">Select country first</option>');
            $('#city').html('<option value="">Select state first</option>'); 
        }
    });

    $('#state').on('change',function(){
        var stateID = $(this).val();
        if(stateID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'state_id='+stateID,
                success:function(html){
                    $('#city').html(html);
                }
            }); 
        }else{
            $('#city').html('<option value="">Select state first</option>'); 
        }
    });
});
</script>
</head>
<body>
<div class="container">
    <?php
    //Include the database configuration file
    include 'dbConfig.php';

    //Fetch all the country data
    $query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");

    //Count total number of rows
    $rowCount = $query->num_rows;
    ?>
    <select id="country">
        <option value="">Select Country</option>
        <?php
        if($rowCount > 0){
            while($row = $query->fetch_assoc()){ 
                echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
            }
        }else{
            echo '<option value="">Country not available</option>';
        }
        ?>
    </select>

    <select id="state">
        <option value="">Select country first</option>
    </select>

    <select id="city">
        <option value="">Select state first</option>
    </select>
</div>
</body>
</html>

CREATE TABLE countries ( country_id int(11) NOT NULL, country_name varchar(50) CHARACTER SET utf8 NOT NULL, status tinyint(1) NOT NULL DEFAULT '1' COMMENT '0:Blocked, 1:Active' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `states` (

state_id int(11) NOT NULL, state_name varchar(50) COLLATE utf8_unicode_ci NOT NULL, country_id int(11) NOT NULL, status tinyint(1) NOT NULL DEFAULT '1' COMMENT '0:Blocked, 1:Active' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE states ADD PRIMARY KEY (state_id);

ALTER TABLE states MODIFY state_id int(11) NOT NULL AUTO_INCREMENT; COMMIT;

CREATE TABLE cities (

city_id int(11) NOT NULL, city_name varchar(50) COLLATE utf8_unicode_ci NOT NULL, state_id int(11) NOT NULL, status tinyint(1) NOT NULL DEFAULT '1' COMMENT '0:Blocked, 1:Active' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE cities ADD PRIMARY KEY (city_id);

ALTER TABLE cities MODIFY city_id int(11) NOT NULL AUTO_INCREMENT;

</div>
  • 写回答

1条回答 默认 最新

  • 斗士狗 2019-01-26 20:20
    关注

    I am unable to replicate or test your AJAX calls and you did not provide an example of the data structure. I would advise you use AJAX to populate all your content instead of mixing in PHP. Consider the following code.

    var countries = [{
        value: "us",
        label: "United States",
        states: [{
          value: "ca",
          label: "California",
          cities: [{
            value: "sf",
            label: "San Francisco"
          }, {
            value: "la",
            label: "Los Angeles"
          }]
        }, {
          value: "or",
          label: "Oregon"
        }, {
          value: "wa",
          label: "Washington"
        }]
      }, {
        value: "mx",
        label: "Mexico"
      },
      {
        value: "ca",
        label: "Canada"
      }
    ];
    $(function() {
      function populateSelect(arr, tObj) {
        $("<option>").appendTo(tObj);
        $.each(arr, function(k, v) {
          $("<option>", {
            value: v.value
          }).data("id", k).html(v.label).appendTo(tObj);
        });
      }
    
      populateSelect(countries, $("#country"));
      $("#state").width($("#country").width() + "px");
      $("#city").width($("#country").width() + "px");
    
      $('#country').on('change', function(e) {
        var c = $("option:selected", this).data("id");
        populateSelect(countries[c].states, $("#state"));
        $("#state").prop("disabled", false);
        /*
        $.ajax({
          type: 'POST',
          url: 'ajaxData.php',
          data: JSON.stringinfy({'country_id': c}),
          success: function(resp) {
            populateSelect(resp, $('#state'));
          }
        });
        */
      });
    
      $('#state').on('change', function(e) {
        var c = $("#country option:selected").data("id");
        var s = $("option:selected", this).data("id");
        populateSelect(countries[c].states[s].cities, $("#city"));
        $("#city").prop("disabled", false);
        /*
        $.ajax({
          type: 'POST',
          url: 'ajaxData.php',
          data: JSON.stringinfy({'state_id': s}),
          success: function(resp) {
            populateSelect(resp, $('#cities'));
          }
        });
        */
      });
    });
    .container {
      width: 280px;
      text-align: center;
    }
    
    .container ul {
      padding: 0;
      margin: 0;
      list-style: none;
    }
    
    .container ul li label {
      width: 120px;
      display: inline-block;
    }
    
    select option {
      font-family: Georgia;
      font-size: 14px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <div class="container">
      <ul>
        <li>
          <label>Country</label>
          <select id="country">
          </select>
        </li>
        <li>
          <label>State</label>
          <select id="state" disabled="true">
          </select>
        </li>
        <li>
          <label>City</label>
          <select id="city" disabled="true">
          </select>
        </li>
      </ul>
    </div>

    In the comments, you can see what you'd do with AJAX. The structure would be the same:

    [
      {
        value,
        label
      }
    ];
    

    I suggest this as you can easily up this to use jQuery UI Autocomplete if you choose.

    Hope this helps.

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?