用sql ajax级联下拉菜单

时间:2016-08-24 11:14:01

标签: javascript php html sql ajax

我有5个表的数据库。每个表都是前一个表的子类,称为:

  • 国家
  • 状态
  • 城市
  • 邮政编码
  • 街道

现在我有3个相互依赖的下拉菜单。因此,当我选择countries: USA时,下一个下拉列表将仅显示美国州等。这是有效的。

但是现在我想扩展到5个下拉菜单,所以再增加2个。

我没有展示我尝试添加的内容,因为它可能只会使它更复杂。

所以我展示了现在正在运行的3个下拉菜单:

档案:ajax.php

<?php
//dbConfig is not added here, but it connects to database
include('dbConfig.php');

if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get 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;

//Display states 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>';
}
}

if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get all city data
$query = $db->query("SELECT * FROM cities WHERE state_id =  ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");

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

//Display cities 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>';
}
}
?>

****The index.php-file**** (I didn't add the css):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="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="select-boxes">
<?php
//Include database configuration file
include('dbConfig.php');

//Get all 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 name="country" 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 name="state" id="state">
    <option value="">Select country first</option>
</select>

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

2 个答案:

答案 0 :(得分:0)

看,我稍微修改了你的代码。

我对您的street&amp; zipcode表列名称或下拉列表。我假设并做到了。 在dropdow或query中需要的地方更改它。 它会对你有所帮助。 通过它。

如果有任何疑问,请随时提出。

<强>的index.php

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>

  </head>
  <body>
    <div class="select-boxes">
      <?php include('dbConfig.php'); //Include database configuration file ?>
      <div class="country">
        <?php
        $query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");
        $rowCount = $query->num_rows;
        ?>
        <select name="country" 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>
      </div>

      <div class="showStateCity">
        <select name="state" id="state">
          <option value="">Select country first</option>
        </select>
        <select name="city" id="city">
          <option value="">Select state first</option>
        </select>

        <select name="zipcode" id="zipcode">
          <option value="">Select City first</option>
        </select>

        <select name="streets" id="streets">
          <option value="">Select Zipcode first</option>
        </select>

      </div>

    </div>
  </body>
</html>
<script src="jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
    $('#country').on('change',function(){
      getStateCityZipCodeStreets();
    });

    $('#state').on('change',function(){
      getStateCityZipCodeStreets();
    });

    $('#city').on('change',function(){
      getStateCityZipCodeStreets();
    });

    $('#zipcode').on('change',function(){
      getStateCityZipCodeStreets();
    });

    function getStateCityZipCodeStreets(){
      var country = $('#country').val();
      var state = $('#state').val();
      var city = $('#city').val();
      var zipcode = $('#zipcode').val();

      $.ajax({
          type:'POST',
          url:'ajaxData.php',
          data:{country_id:country, state_id :state, city_id : city, zipcode_id : zipcode},
          cache:false,
          success:function(data){
            $('.showStateCity').html(data);
          }
      }); 
    }
  });
</script>

<强> ajaxData.php

<?php
//dbConfig is not added here, but it connects to database
include('dbConfig.php');

/*States*/
$queryState = "SELECT * FROM states WHERE 1=2";
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
  $queryState = "SELECT * FROM states WHERE status = 1 AND country_id =".$_POST['country_id']." ORDER BY state_name ASC";
}
$execQueryState = $db->query($queryState);
$rowCountState = $execQueryState->num_rows;

/*City*/
$queryCity = "SELECT * FROM cities WHERE 1=2";
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
  $queryCity = "SELECT * FROM cities WHERE status = 1 AND state_id".$_POST['state_id']." ORDER BY city_name ASC";
}
$execQueryCity = $db->query($queryCity);
$rowCountCity = $execQueryCity->num_rows;

/*ZipCode*/
$queryZipcode = "SELECT * FROM zipcode WHERE 1=2";
if(isset($_POST["city_id"]) && !empty($_POST["city_id"])){
  $queryZipcode = "SELECT * FROM zipcode WHERE status = 1 AND city_id".$_POST['city_id']." ORDER BY zipcode ASC";
}
$execQueryZipCode = $db->query($queryZipcode);
$rowCountZipCode = $execQueryZipCode->num_rows;

/*Streets*/
$queryStreets = "SELECT * FROM streets WHERE 1=2";
if(isset($_POST["zipcode_id"]) && !empty($_POST["zipcode_id"])){
  $queryStreets = "SELECT * FROM streets WHERE status = 1 AND zipcode_id".$_POST['zipcode_id']." ORDER BY street_name ASC";
}
$execQueryStreets = $db->query($queryStreets);
$rowCountStreets = $execQueryStreets->num_rows;
?>

<select name="state" id="state">
  <option value="">Select country first</option>
  <?php
  if($rowCountState > 0){
    while($rowState = $execQueryState->fetch_assoc()){ 
    ?>
    <option value="<?php echo $rowState['state_id'];?>"><?php echo $rowState['state_name'];?></option>
  <?php }
  } else {?>
  <option value="">State Not Available</option>
  <?php }?>
</select>

<select name="city" id="city">
  <option value="">Select state first</option>
  <?php
  if($rowCountCity > 0){
    while($rowCity = $execQueryCity->fetch_assoc()){ 
    ?>
    <option value="<?php echo $rowCity['city_id'];?>"><?php echo $rowCity['city_name'];?></option>
  <?php }
  } else {?>
  <option value="">City Not Available</option>
  <?php }?>
</select>

<select name="zipcode" id="zipcode">
  <option value="">Select City first</option>
  <?php
  if($rowCountZipCode > 0){
    while($rowZipCode = $execQueryZipCode->fetch_assoc()){ 
    ?>
    <option value="<?php echo $rowZipCode['zipcode_id'];?>"><?php echo $rowZipCode['zipcode'];?></option>
  <?php }
  } else {?>
  <option value="">ZipCode Not Available</option>
  <?php }?>
</select>

<select name="streets" id="streets">
  <option value="">Select ZipCode first</option>
  <?php
  if($rowCountStreets > 0){
    while($rowStreets = $execQueryStreets->fetch_assoc()){ 
    ?>
    <option value="<?php echo $rowStreets['street_id'];?>"><?php echo $rowStreets['street_name'];?></option>
  <?php }
  } else {?>
  <option value="">Streets Not Available</option>
  <?php }?>
</select>

答案 1 :(得分:0)

您需要创建另外两个表格邮政编码和街道,并在邮政编码表中添加city_id,在街道表格中添加zip_id

$('#city').on('change',function(){
    var cityId = $(this).val();
    if(cityId){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            data:'city_id='+cityId,
            success:function(html){
                $('#zipcode').html(html);
            }
        }); 
    }else{
        $('#zipcode').html('<option value="">Select zipcode first</option>'); 
    }
});
});

$('#zipcode').on('change',function(){
    var zipId = $(this).val();
    if(zipId){
        $.ajax({
            type:'POST',
            url:'ajaxData.php',
            data:'zip_id='+zipId,
            success:function(html){
                $('#streets').html(html);
            }
        }); 
    }else{
        $('#streets').html('<option value="">Select Streets first</option>'); 
    }
});
});

Jquery Scrtipt

@Test
public void testFacetMethodEnum()   throws SolrServerException {
    SimpleFacetQuery query = new SimpleFacetQuery();
    query.addCriteria(new Criteria("coumn_name1").is("value1"));
    query.addCriteria(new Criteria("coumn_name2").is("value2"));
    query.addProjectionOnField("projection_1");

    FacetOptions facetOptions = new FacetOptions("facet_field");
    facetOptions.setFacetLimit(1000);
    query.setFacetOptions(facetOptions);

    QueryParsers queryParsers = new QueryParsers();
    SolrQuery solrQuery = queryParsers.getForClass(query.getClass()).constructSolrQuery(query);
    solrQuery.setParam(FacetParams.FACET_METHOD, FacetParams.FACET_METHOD_enum);

    QueryResponse reponse = Your_SolrTemplate.getSolrOperations().getSolrServer().query(solrQuery);
    assertNotNull(reponse);
}

Php代码与状态只需更改表名和字段

相同

通过使用此功能,您可以获得邮政编码和街道的级联下拉菜单。