问题
I have two drop down lists one is depended on other if one value selected the other one load same values from database. for example if i select one country other load same cities that country.
<select name="A" class="input_text" id="A">
<?php
include 'config/config.php';
$sql="SELECT * FROM department ORDER BY Dept ASC";
$result=mysql_query($sql);$options="";
while ($row=mysql_fetch_array($result)){
$did=$row["DeptCode"];
$depts=$row["Dept"];
$options.="<OPTION value='$did'>".$depts;}?>
<option value="0">Select...</option>
<?php echo $options; ?>'
</option>
</select>
<select name="B" class="input_text" id="B">
<?php
include 'config/config.php';
$sql="SELECT * FROM department WHERE DeptCode=$dpttitle";
$result=mysql_query($sql);$options="";
while ($row=mysql_fetch_array($result)){
$did=$row["DeptCode"];
$depts=$row["Dept"];
$options.="<OPTION value='$did'>".$depts;}?>
<option value="0">Select...</option>
<?php echo $options; ?>
</option>
</select>
<script type="text/javascript">
A.onblur = function() {
B.value = this.value;};
</script>
回答1:
You're looking for "ajax" functionality. Try looking into $.get(url,data,success);
using JQuery
First, remove dropbox B and replace it with a div with id="B"
$("#A").change(loadCities);
function loadCities(e){
// prepare get statement
var url = "http://www.yoursite.com/ajax/getCities";
var data = {
country : $("#A").val()
};
$.get(url, data, loadCitiesComplete);
}
function loadCitiesComplete(data){
$("#B").html(data);
}
That url : "http://www.yoursite.com/ajax/getCities"
php should look something like
<?
if(isset($_GET['country'])){
$html = '<select name="B" class="input_text" id="B">';
include 'config/config.php';
$dpttitle = mysql_real_escape_string($_GET['country']);
$sql="SELECT * FROM department WHERE DeptCode=$dpttitle";
$result=mysql_query($sql);$options="";
while ($row=mysql_fetch_array($result)){
$did=$row["DeptCode"];
$depts=$row["Dept"];
$html .="<OPTION value='$did'>".$depts;}?>
$html .= '<option value="0">Select...</option>';
$html .= '</option>';
$html .= '</select>';
echo $html;
}
?>
Obviously the php should use the country $_GET var properly, use PDO or MySQLi with prepared statements for safety, etc. But hopefully this'll get you moving in the right direction.
来源:https://stackoverflow.com/questions/16514594/in-php-and-jquery-make-one-drop-down-depend-on-another-drop-down-list