用PostgreSQL的PHP和AJAX创建动态的依赖性下拉菜单(详细教程)

175 阅读2分钟

通过自动填充下拉,你可以根据父下拉的选择来限制用户的选择。

每次选择被改变时,子下拉的数据就会被改变。

在本教程中,我展示了如何使用jQuery AJAX和PHP创建具有PostgreSQL数据的动态依赖下拉。

Create dynamic dependent dropdown with PostgreSQL PHP and AJAX

下载


内容

  1. 表的结构
  2. 配置
  3. HTML
  4. 术语
  5. jQuery
  6. 输出
  7. 结论

1.表 的结构

我在这个例子中使用了3个表 -

国家表(存储国家的记录)

CREATE TABLE countries (
  id serial PRIMARY KEY,
  name varchar(80) NOT NULL
)

状态表(存储国家的状态) - 城市表(存储国家的城市

CREATE TABLE states (
  id serial PRIMARY KEY,
  name varchar(80) NOT NULL,
  country_id bigint NOT NULL
)

城市表(存储各州的城市)

CREATE TABLE cities (
  id serial PRIMARY KEY,
  name varchar(80) NOT NULL,
  state_id bigint NOT NULL
)

2.配 置

创建一个新的config.php 文件。

完成的代码

<?php

$host = "localhost";
$user = "postgres";
$password = "root";
$dbname = "tutorial";
$con = pg_connect("host=$host dbname=$dbname user=$user password=$password");

if (!$con) {
   die('Connection failed.');
}

3.H TML

countries 表中获取记录并创建3个<select> 元素:

  • 第一个<select > 元素是用来显示获取的countries
  • 第二个元素是使用jQuery AJAX来显示基于国家选择的州,和
  • 第三个是使用jQuery AJAX来显示基于州选择的城市。

完成的代码

<?php
include "config.php";

$sql = "select * from countries order by name";
$result = pg_query($con, $sql);
?>
<table>
   <tr>
      <td>Country</td>
      <td>
         <select id="country">
            <option value="0" >– Select Country –</option>
            <?php
            while ($row = pg_fetch_assoc($result) ){

               $id = $row['id'];
               $name = $row['name'];

               echo "<option value='".$id."' >".$name."</option>";
            }
            ?>
         </select>
      </td>
   </tr>

   <tr>
      <td>State</td>
      <td>
         <select id="state" >
            <option value="0" >– Select State –</option>
         </select>
      </td>
   </tr>

   <tr>
      <td>City</td>
      <td>
         <select id="city" >
            <option value="0" >– Select City –</option>
         </select>
      </td>
   </tr>
</table>

4.P HP

创建ajaxfile.php 文件。

处理2个AJAX请求 -

  • 如果 request==getStates根据request == 'getStates' -根据`country_id 的值从states 表中获取记录并分配给result。在result` 。在`result 上循环,用idname 键初始化$data` 数组。

以JSON格式返回$data

  • 如果 request==getCities根据request == 'getCities' -根据`state_id 的值从cities 表中获取记录并分配给result。在result` 。在`result 上循环,用idname 的键初始化$data` 数组。

以JSON格式返回$data

完成的代码

<?php
include 'config.php';

$request = "";
if(isset($_POST['request'])){
   $request = $_POST['request'];
}

// Get states
if($request == 'getStates'){
   $country_id = 0;
   $result = array();$data = array();

   if(isset($_POST['country_id'])){
      $country_id = $_POST['country_id'];

      $sql = "select * from states where country_id=$1";
      $result = pg_query_params($con, $sql, array($country_id));

      while ($row = pg_fetch_assoc($result) ){

         $id = $row['id'];
         $name = $row['name'];

         $data[] = array(
            "id" => $id,
            "name" => $name
         );

      }
   }

   echo json_encode($data);
   die;

}

// Get cities
if($request == 'getCities'){
   $state_id = 0;
   $result = array();$data = array();

   if(isset($_POST['state_id'])){
      $state_id = $_POST['state_id'];

      $sql = "select * from cities where state_id=$1";
      $result = pg_query_params($con, $sql, array($state_id));

      while ($row = pg_fetch_assoc($result) ){

         $id = $row['id'];
         $name = $row['name'];

         $data[] = array(
            "id" => $id,
            "name" => $name
         );

      }
   }

   echo json_encode($data);
   die;
}

5. jQuery

#country#state 上定义change 事件:

  • country -如果选择了一个国家,则清空#state ,和#city 下拉菜单。发送AJAX POST请求到ajaxfile.php ,将{request: 'getStates', country_id: country_id} 作为data ,并设置dataType: 'json'

在成功的情况下,对response 进行回调循环,并在#state 中添加<option >

  • state -如果选择了一个状态,那么清空#city 下拉菜单,并发送AJAX POST请求到ajaxfile.php ,将{request: 'getCities', state_id: state_id} 作为data ,并设置dataType: 'json'

在成功回调时,在response 上循环,并在#city 中添加<option >

完成的代码

$(document).ready(function(){

   // Country
   $('#country').change(function(){

      // Country id
      var country_id = $(this).val();

      // Empty the dropdown
      $('#state').find('option').not(':first').remove();
      $('#city').find('option').not(':first').remove();

      // AJAX request
      $.ajax({
         url: 'ajaxfile.php',
         type: 'post',
         data: {request: 'getStates', country_id: country_id},
         dataType: 'json',
         success: function(response){

            var len = 0;
            if(response != null){
               len = response.length;
            }

            if(len > 0){
               // Read data and create <option >
               for(var i=0; i<len; i++){

                  var id = response[i].id;
                  var name = response[i].name;

                  var option = "<option value='"+id+"'>"+name+"</option>";

                  $("#state").append(option);
               }
            }
         }
      });
   });

   // Country
   $('#state').change(function(){

      // State id
      var state_id = $(this).val();

      // Empty the dropdown
      $('#city').find('option').not(':first').remove();

      // AJAX request
      $.ajax({
         url: 'ajaxfile.php',
         type: 'post',
         data: {request: 'getCities', state_id: state_id},
         dataType: 'json',
         success: function(response){

            var len = 0;
            if(response != null){
               len = response.length;
            }

            if(len > 0){
               // Read data and create <option >
               for(var i=0; i<len; i++){

                  var id = response[i].id;
                  var name = response[i].name;

                  var option = "<option value='"+id+"'>"+name+"</option>";

                  $("#city").append(option);
               }
            }

         }
      });
   });

});

6.输 出

查看输出


7.总 结

在这个例子中,我自动填充了两个下拉菜单,但是你可以按照同样的步骤在更多的下拉菜单中添加它。

如果数据没有加载到下拉菜单中,请使用浏览器的网络标签进行调试。