0

我正在尝试制作级联下拉列表,我希望当用户选择区域然后相应地填充城市下拉列表..

JS

$(document).ready(function() {
    $('#region').change(function() {
        var region = $(this).val();
        $.post('get_region.php', {
            region: region
        }, function(data) {
            $('#district_div').html(data);
        });
    });

PHP

<?php
require_once('../db/connect.php');

$region=$_POST['region'];

$q=mysql_query("select name from city where region='$region'");

$row=mysql_fetch_array($q);
echo $row['name']; 
?>

HTML*强文本*

 <div class="controls">

                       <select class="bootstrap-select" name="region" id="region">
                                          <option value="">Choose</option>
                                      //from database
                                          <?php echo $region_result; ?>

           </select>
  </div>

                       <select class="bootstrap-select" name="district" id="district" >

                             <div id='district_div'></div>         

          </select>
4

3 回答 3

1
-for JS it should be like this-

$(document).ready(function() {
    $('#region').change(function() {
        var region = $(this).val();
        $.post('get_region.php', {
            region: region
        }, function(data) {
            $('#district').html(data); // I change this part
        });
    });


-for php-

<?php
require_once('../db/connect.php');

$region=$_POST['region'];

$q=mysql_query("select name from city where region='$region'");

while($row = mysql_fetch_array($q)){
   echo "<option>".$row['name']."</option>";
}

?>


-for the html

<div class="controls">
   <select class="bootstrap-select" name="region" id="region">
      <option value="">Choose</option>
      //from database
      <?php echo $region_result; ?>
    </select>

     <select class="bootstrap-select" name="district" id="district" >

     </select>     <!--you don't need to put a div in the select tag-->
</div>
于 2013-08-22T09:37:26.140 回答
0

您正在尝试在选择框中写入纯文本。尝试以 HTML 格式编写:

<option>name</option>

在您的 JS 中,替换以下行:

$('#district_div').html(data);

和:

$('#district').html(data);

删除 ID 为“district_div”的 DIV。SELECT 中不能有 DIV。在 PHP 中,最后一行是:

echo "<option>$row[name]</option>";
于 2013-07-04T17:56:12.543 回答
0

你错过了一些片段

// will echo the name value of one row
    $row=mysql_fetch_array($q);
    echo $row['name']; 

尝试

$results = array();
while($row = mysql_fetch_array($q)){
$results[] = '<option>.'$row['name'].'</option>';
}
$optionString= implode(' ', $results);
echo $optionsString;
于 2013-07-04T17:58:27.330 回答