【问题标题】:How to make a Cascading Drop Down List in PHP using jQuery如何使用 jQuery 在 PHP 中制作级联下拉列表
【发布时间】:2011-10-14 23:56:12
【问题描述】:

我的数据库由国家和城市组成。

第一个案例 - 成功完成:

  1. 国家/地区列表在页面加载时填充到下拉框中
  2. 城市列表在页面加载时填充到下拉框中 - 填充的城市列表 基于默认国家/地区。

第二种情况 - 没能成功:

  1. 用户更改国家/地区
  2. 城市列表将根据所选国家/地区进行更改

我知道我必须使用 jQuery/Ajax。我尝试过,但由于缺乏编程经验,我无法解决我的问题。我的列表是从数据库而不是 XML 中获取的。我只需要一个快速的解决方案,我需要保持简单和愚蠢。

我使用的是常规的 PHP 编码风格,而不是面向对象的。

我该怎么做?任何相关资源将不胜感激。

【问题讨论】:

    标签: php ajax jquery


    【解决方案1】:

    index.php

    <?php
    require_once './db.php';
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>StackOverFlow</title>
    
        <script
                src="https://code.jquery.com/jquery-3.4.1.min.js"
                integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
                crossorigin="anonymous">
        </script>
        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="text/javascript" src="app.js"></script>
    </head>
    <body>
    
        <?php
        // In this part of the code i'm building the  select box options
        $sql = "SELECT thana FROM locations group by thana";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        ?>
    
        <select name="Thana" class="thana-select-box">
            <option></option>
        <?php
        while ($row = $stmt->fetch()){ ?>
            <option value="<?=$row['thana']?>"><?=$row['thana']?></option>
       <?php } ?>
        </select>
    
        <select name="Area" class="area-select-box">
    
        </select>
    
    
    
    
    </body>
    </html>

    db.php

    <?php
    
    $username = 'your username';
    $password = 'your password';
    $host = 'localhost';
    $dbname = 'test';
    
    $conn = new PDO("mysql:host=$host;dbname=$dbname",$username, $password
        ,
        array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_PERSISTENT => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ));

    get_options.php

    <?php
    require_once 'db.php';
    
    $thana = $_REQUEST['thana'];
    
    $sql = "SELECT area FROM locations where thana='$thana'";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    
    $options = [];
    
    while ($row = $stmt->fetch()){
        $options[] = $row['area'];
    
    }
    
    echo json_encode($options);

    app.js:

    $(document).ready( function(){
    
        $(document).on('change', '.thana-select-box', function(e){
    
            let fd = new FormData();
            let thana = $(this).val();
            fd.append('thana', thana);
            // In this part of the code according to the selected thana, we are going to fetch
            // the rows from the second table Area, the php will return a json structure that contains the  rows
            // or more with the  Area that belong to thana.
    
            $.ajax({
                url: "get_options.php",
                type: "POST",
                data: fd,
                processData: false,
                contentType: false,
    
                complete: function (results) {
                    try {
                        let str = JSON.parse(results.responseText);
                        updateDOM(str);
                        console.log(str)
                    } catch (e) {
                        console.error(e.message);
                    }
                },
            });
    
    
        });
    
    
    
    
        updateDOM = (options) => {
    
            let areaSelectBox = $('.area-select-box');
            let options_dom = '';
            options.map((value)=>{
    
                options_dom += `<option value="${value}">${value}</option>`;
            });
    
    
            areaSelectBox.html ('');
            areaSelectBox.append(options_dom);
    
    
        };
    
    
    });

    【讨论】:

      【解决方案2】:

      写入数据而不是 obj。它工作得很好

      【讨论】:

        【解决方案3】:
        $("#country").change(function(){
            $('#city').find('option').remove().end(); //clear the city ddl
            var country = $(this).find("option:selected").text();
            alert(country);
            //do the ajax call
            $.ajax({
                url:'getCity.php'
                type:'GET',
                data:{city:country},
                dataType:'json',
                cache:false,
                success:function(data){
        
                data=JSON.parse(data); //no need if dataType is set to json
                 var ddl = document.getElementById('city');                      
        
                 for(var c=0;c<obj.length;c++)
                      {              
                       var option = document.createElement('option');
                       option.value = obj[c];
                       option.text  = obj[c];                           
                       ddl.appendChild(option);
                      }
        
        
            },
                error:function(jxhr){
                alert(jxhr.responseText);
        
            }
            }); 
        
        });
        

        在你的 getCity.php 中

        $country = $_GET['city'];
        
        //do the db query here
        
        $query  = "your query";
        $result = mysql_query($query);
        $temp = array();
        while ($row = mysql_fetch_assoc($result)) {
        
         if(empty($temp))
         {
           $temp=array($row['city']);
         }
         else
         {  
           array_push($temp,$row['city']);
         }
        
        }
        echo (json_encode($temp));
        

        【讨论】:

        • 请检查您的代码 - 您将变量数据和 obj 混淆了。
        【解决方案4】:

        您可以通过使用 jquery 的 .change() 方法对选择框值的更改进行 ajax 调用来做到这一点。 api.jquery.com/change/

        【讨论】:

          猜你喜欢
          • 2012-10-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-12
          • 2012-07-01
          • 2016-12-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多