动态填充下拉列表不起作用。选择一个字段后,不会填充我的下拉菜单

时间:2019-06-13 02:42:27

标签: php ajax

我正在WAMP上运行我的项目。

我有一个包含2个表的数据库:country和state分别具有字段值id,country和id,country_id(国家表的id),state。

我已经创建了index.php,db.php,ajax.js,get-states.php。我选择国家/地区后的下拉菜单无效。

我也发布了我的代码。问题出在哪里?请帮忙。

我已经发布了文件代码:index.php,ajax.js,get-states.php。

index.php

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>

<?php include("db.php");?>
<div class="">
    <label>Country :</label>
    <select name="country" id="country">
      <option value=''>------- Select --------</option>
      <?php 
      $sql = "select * from `countries`";
      $res = mysqli_query($con, $sql);
      if(mysqli_num_rows($res) > 0) {
        while($row = mysqli_fetch_object($res)) {
          echo "<option value='".$row->id."'>".$row->country."</option>";
        }
      }
      ?>
    </select>

    <label>State :</label>
    <select name="state" id="state"><option>------- Select --------</option></select>
  </div>

ajax.php

$(document).ready(function() {
  $("#country").change(function() {
    var country_id = $(this).val();
    if(country_id != "") {
      $.ajax({
        url:"get-states.php",
        data:{c_id:country_id},
        type:'POST',
        success:function(response) {
          var resp = $.trim(response);
          $("#state").html(resp);
        }
      });
    } else {
      $("#state").html("<option value=''>------- Select --------</option>");
    }
  });
});

get-states.php

<?php include("db.php"); ?>
<?php
if(isset($_POST['c_id'])) {
  $sql = "select * from `states` where `country_id`=".mysqli_real_escape_string($con, $_POST['c_id']);
  $res = mysqli_query($con, $sql);
  if(mysqli_num_rows($res) > 0) {
    echo "<option value=''>------- Select --------</option>";
    while($row = mysqli_fetch_object($res)) {
      echo "<option value='".$row->id."'>".$row->state."</option>";
    }
  }
} else {
  header('location: ./');
}
?>

1 个答案:

答案 0 :(得分:0)

尝试一下:

// html

<select name="country"
                id="country"
                onChange="getState(this.value);">
                <option value disabled selected>Select Country</option>
             if(mysqli_num_rows($res) > 0) {
        while($row = mysqli_fetch_object($res)) {
          echo "<option value='".$row->id."'>".$row->country."</option>";
        }
      }
      ?>
    </select>

// ajax

function getState(val) {
    $.ajax({
    type: "POST",
    url: "get-State.php",
    data:'country_id='+val,
    success: function(data){
        $("#state").html(data);
    }
    });
}