我使用这段代码填充来自数据库的城市和州的下拉列表。但是现在我想要一个动态下拉菜单,我可以在其中选择州,根据州的情况,该州的城市将会有人口。我需要你的帮助,提前谢谢你。
$query3 = "SELECT state FROM states";
$result3 = mysqli_query($db,$query3);
$query4 = "SELECT city FROM cities";
$result4 = mysqli_query($db,$query4);
if (!$result3) {
echo("Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);
}
if (!$result4) {
echo("Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);
}
<select style="font-family:Arial, Helvetica, sans-serif; font-size:13px;" id="state" name="state" >
<option></option>
<?php
while ($row = mysqli_fetch_assoc($result3)){
echo '<option value="' . $row['state'] . '">' . $row['state']. '</option>';
}
?>
</select>
<select style="font-family:Arial, Helvetica, sans-serif; font-size:13px;" id="city" name="city" >
<option></option>
<?php
while ($row = mysqli_fetch_assoc($result4)){
echo '<option value="' . $row['city'] . '">' . $row['city']. '</option>';
}
?>
</select>
您必须使用AJAX。
第一个下拉框(状态)。在更改时,您需要触发一个ajax调用来获取该状态下的城市。
的例子:
<?php
$query3 = "SELECT state FROM states";
$result3 = mysqli_query($db,$query3);
?>
<select id="statesSelectBox" name="state" onchange="getStates();">
<?php
while ($row = mysqli_fetch_assoc($result3)){
echo '<option value="' . $row['state'] . '">' . $row['state']. '</option>';
}?>
</select>
<div id="updateCities">
</div>
<script>
function getStates(){
$.ajax({
url:'mydomain.com/getCities.php',
cache:false,
data:{state:$('#statesSelectBox').val()},
beforeSend:function(){
// do something here. possibly a loader
},
success:function(response){
// remove the loader here
$('#updateCities').html(response);
}
})
}
</script>
在getcities。php中应该有
<?php
$query4 = "SELECT city FROM cities WHERE your_state_id = ".$_POST['state'];
$result4 = mysqli_query($db,$query4);
?>
<select>
<option>-- Select City --</option>
<?php while ($row = mysqli_fetch_assoc($result4)){
echo '<option value="' . $row['city'] . '">' . $row['city']. '</option>';
} ?>
</select>
我只是在没有测试的情况下快速编写了这段代码。这将帮助您了解如何采用该方法。