【问题标题】:how to Display dynamic dropdown using table data如何使用表格数据显示动态下拉列表
【发布时间】:2021-05-16 19:44:21
【问题描述】:

我需要根据从下拉列表中选择的国家/地区显示状态。 它使用表数据通过 AJAX 获取和查找相关数据

这是我的 HTML 标记

<label for="country">Country</label>
                <select class="form-control" id="country">
                    <option value="">Select Country</option>
                    <?php 
                        $query = "SELECT * FROM countries";
                        $result = $con->query($query);
                        if ($result->num_rows > 0) {
                            while ($row = $result->fetch_assoc()) {
                                echo "<option value='{$row["country_refer"]}'>{$row['country_name']}</option>";
                            }
                        }
                        else
                        {
                            echo "<option value=''>Country not available</option>"; 
                        }
                    ?>
                </select><br>

                <!-- State drop down -->
                <label for="state">State</label>
                <select class="form-control" id="state">
                    <option value="">Select State</option>
                </select>
                <br>

这是我将选项值发布到 action.php 页面的 javascript 代码

<script type="text/javascript">
$(document).ready(function(){
    // Country dependent ajax
    $("#country").on("change",function(){
        var countryId = $(this).val();
        alert(countryId);
        if (countryId) {
            $.ajax({
                url :"action.php",
                type:"POST",
                cache:false,
                data:{countryId:countryId},
                success:function(data){

                    $("#state").html(data);

                    alert(data);

                }
            });
        }
    });
});

这是我的 action.php 页面

<?php 
// Include the database config file 
include_once 'dbConfig.php';

// Get country id through state name

$countryId = $_REQUEST['countryId'];

if (!empty($countryId)) {
    // Fetch state name base on country id
    $query = "SELECT * FROM states WHERE country_refer = {$countryId}";

    echo "$query";
    $result = $con->query($query);

    if ($result->num_rows > 0) 
    {
        while ($row = $result->fetch_assoc()) {

            echo '<option value="'.$row['id'].'">'.$row['state_name'].'</option>'; 

        }
    }
    else{
        echo '<option value="">State not available</option>'; 
    }
}

?>

状态没有出现在我的下拉菜单中并显示此错误我已在此处附上屏幕截图。

我使用 alert 来查找这里发生的情况,它会抛出此错误。

这是我的 Sql 文件

   CREATE TABLE `countries` (
       `id` int(11) NOT NULL,
       `country_refer` varchar(50) NOT NULL,
       `country_name` varchar(50) NOT NULL
       ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

      INSERT INTO `countries` (`id`, `country_refer`,   `country_name`VALUES
      (1, 'India', 'India'),
      (2, 'Pakistan' ,'Pakistan'),
      (3, 'America','America'),
      (4, 'China','China');



CREATE TABLE `states` (
     `id` int(11) NOT NULL,
     `country_refer` varchar(50) NOT NULL,
     `state_name` varchar(50) NOT NULL
     ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


      INSERT INTO `states` (`id`, `country_refer`, `state_name`) VALUES
          (1, 'India', 'Andhra Pradesh'),
          (2, 'India', 'Gujarat'),
          (3, 'America', 'Florida'),
          (4, 'America', 'New Jersey'),
          (5, 'China', 'Chongqing'),
          (6, 'China', 'Shanghai'),
          (7, 'India', 'Delhi'),
          (8, 'India', 'Mumbai');

【问题讨论】:

  • 你想要国家和州名而不是 id 吗??
  • 是的...我不需要

标签: php mysql ajax


【解决方案1】:

最后我找到了使用 MYSQL 表格文本数据显示动态下拉列表的解决方案。

我的 AJAX 库 CDN(需要放在页脚位置)

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

我的数据库配置代码config.php

<?php

$con = mysqli_connect("localhost","root","","demos");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }  

?>

我的 HTML 和 PHP 代码显示下拉

 <!-- Drop down for state  -->

              <select onChange="getdistrict(this.value);"  name="state" id="state" class="form-control" >

                <option value="">Select</option>

                            <?php $query =mysqli_query($con,"SELECT * FROM state");
                      while($row=mysqli_fetch_array($query))
                      { ?>
                          <option value="<?php echo $row['Statenme'];?>"><?php echo $row['StateName'];?></option>
                      <?php
                      }
                      ?>
              </select>

                <!-- Drop down for district  -->

              <select name="district" id="district-list" class="form-control">
                <option value="">Select</option>
              </select>

我的 java 脚本代码发布选项值以使用 AJAX 过滤区域。这里我将数据发布到 get_district.PHP 页面。

<script>
                function getdistrict(val) {
                  $.ajax({
                  type: "POST",
                  url: "get_district.php",
                  data:'state_nme='+val,
                  success: function(data){
                    $("#district-list").html(data);
                  }
                  });
                }
              </script> 

我的 get_district.php 代码

<?php

require_once("config.php");

if(!empty($_POST["state_nme"])) 
{
    $query =mysqli_query($con,"SELECT * FROM district WHERE Statenme = '" . $_POST["state_nme"] . "'");
?>
<option value="">Select District</option>
<?php
    while($row=mysqli_fetch_array($query))  
{
?>
    <option value="<?php echo $row["DistrictName"]; ?>"><?php echo $row["DistrictName"]; ?></option>
<?php
}
}

?>

这是我的 sql 文件

               CREATE TABLE `state` (
              `Statenme` varchar(100)  NOT NULL,
              `StateName` varchar(150) DEFAULT NULL
            ) ENGINE=MyISAM DEFAULT CHARSET=latin1;



            INSERT INTO `state` (`Statenme`, `StateName`) VALUES
            ('Andaman and Nicobar Island (UT)', 'Andaman and Nicobar Island (UT)'),
            ('Andhra Pradesh', 'Andhra Pradesh'),
            ('Arunachal Pradesh', 'Arunachal Pradesh'),
            ('Assam', 'Assam');


            CREATE TABLE `district` (
              `DistCode` int(11) NOT NULL,
              `Statenme` varchar(100) DEFAULT NULL,
              `DistrictName` varchar(200) DEFAULT NULL
            ) ENGINE=MyISAM DEFAULT CHARSET=latin1;



            INSERT INTO `district` (`DistCode`, `Statenme`, `DistrictName`) VALUES
            (1, 'Andaman and Nicobar Island (UT)', 'North and Middle Andama'),
            (2, 'Andaman and Nicobar Island (UT)', 'South Andama'),
            (3, 'Andaman and Nicobar Island (UT)', 'Nicobar'),
            (4, 'Andaman and Nicobar Island (UT)', 'Anantapur'),
            (5, 'Andaman and Nicobar Island (UT)', 'Chittoor'),
            (6, 'Andhra Pradesh', 'East Godavari'),
            (7, 'Andhra Pradesh', 'Guntur'),
            (8,'Andhra Pradesh', 'Krishna'),
            (9, 'Andhra Pradesh', 'Kurnool'),
            (10, 'Andhra Pradesh', 'Prakasam'),
            (11, 'Andhra Pradesh', 'Srikakulam'),
            (12, 'Andhra Pradesh', 'Sri Potti Sri Ramulu Nellore');

我居然找到了这个解决方案here

非常感谢... :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-08
    • 2014-02-25
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多