我的代码基于codexworld.com的代码段 但我有一个数据库(coin_database),其中包含以下列:
id|coin_name|coin_country|value
1 |MapleLeaf|Canada |5dollars
2 |Panda |China |10yuan
我想建立3阶段表格,首先你选择国家,而不是只有来自这个国家的硬币类型和之后的可用价值(1盎司,5美元等)。
我有2个文件: 的的index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/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='+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:'name='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
<?php
//Include the database configuration file
include 'db_conn.php';
//Fetch all the country data
$query = $conn->query("SELECT DISTINCT coin_country FROM coin_database ORDER BY coin_country ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select id="country">
<option value="">Country</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['coin_country'].'">'.$row['coin_country'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<select id="state">
<option value="">Coin</option>
</select>
<select id="city">
<option value="">Value</option>
</select>
ajaxData.php
<?php
//Include the database configuration file
include 'db_conn.php';
if(!empty($_POST["country"])){
//Fetch all state data
$query = $conn->query("SELECT DISTINCT coin_name, coin_country, value, id FROM `coin_database` WHERE `coin_country` = 'Canada' ORDER BY `coin_name` DESC ");
//Count total number of rows
$rowCount = $query->num_rows;
//State option list
if($rowCount > 0){
echo '<option value="">Coin</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['id'].'">'.$row['coin_name'].'</option>';
}
}else{
echo '<option value="">Error</option>';
}
}
elseif(!empty($_POST["name"])){
//Fetch all city data
$query = $conn->query("SELECT DISTINCT `value` FROM `coin_database` WHERE `coin_name` = 'MapleLeaf' ORDER BY `id` DESC ");
//Count total number of rows
$rowCount = $query->num_rows;
//City option list
if($rowCount > 0){
echo '<option value="">Value</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['id'].'">'.$row['value'].'</option>';
}
}else{
echo '<option value="">Value not available</option>';
}
}
?>
它适用于非动态值(加拿大,MapleLeaf),但是当我尝试将变量放入变量时出现错误。