我正在尝试创建一个动态下拉列表,其中城市根据从MYSQL数据库中选择的状态填充。
第一个下拉列表从数据库填充正常,在我测试它时给出状态名称和state_id。
第二次下拉不会填充。我认为这是因为我正在使用fetch.php文件发送和接收问题。
我认为Ajax是正确的。 Fetch.php就在我的文件结构中的index.php旁边,所以它应该能够找到它。
已经尝试调整fetch.php,因此它不必连接到db,只会回显带有文本的简单选项,但这仍然不会在城市下拉列表中更新。新的,所以任何帮助将不胜感激。
Index.php中的HTML代码:
<?php require_once('../private/initialize.php'); ?>
<?php include(SHARED_PATH . '/header.php'); //SHARED_PATH located in initialize.php ?>
<div id="main-container">
<form action="" id="cost_form" method="post" onsubmit="return false;">
<div id="select-container">
<fieldset class="fieldset">
<div class="custom-select" >
<select id="state" name="state" class = "form-control" onchange="get_cities(this.value);" >
<option value="" >Select State</option>
<?php $state_set = find_all_states();
while ($state = mysqli_fetch_assoc($state_set)) {
echo '<option value="'.h($state["state_id"]).'">'.$state["state_name"].'</option>';}
?>
</select>
</div>
<div class="custom-select" >
<select id="city" name="city" class="form-control">
<option value="1">Select City</option>
</select>
</div>
<div id="total_price"></div>
</fieldset>
</div>
</form>
</div>
<?php include(SHARED_PATH . '/footer.php'); //SHARED_PATH located in initialize.php ?>
<script type="text/javascript">
function get_cities(val) {
$.ajax({
type: "POST",
url: "fetch.php",
data:'state_id='+val,
success: function(data){
$("#city").html(data);
}
});
}
</script>
Fetch.php代码:
<?php require_once('../private/initialize.php'); ?>
<?php
if(isset($_POST['state_id'])) {
$id = $_POST['state_id'];
$city_set = find_city_by_id($id);
while ($city = mysqli_fetch_assoc($city_set)) {
echo '<option value="'.h($city["city_multiplier"]).'">'.$city["city_name"].'</option>';}
}
?>
查询函数,通过Initialize.php访问:
<?php
function find_all_states() {
global $db;
$sql = "SELECT * FROM states ";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;
}
function find_city_by_id($id) {
global $db;
$sql = "SELECT * FROM cities WHERE state_id ='".$id."'";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;
}
?>
数据库,通过Initialize.php访问:
<?php
require_once ('db_credentials.php');
function db_connect() {
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
confirm_db_connect();
return $connection;
}
function db_disconnect($connection) {
if(isset($connection)) {
mysqli_close($connection);
}
}
function confirm_db_connect() {
if(mysqli_connect_errno()) {
$msg = "Database connection failed: ";
$msg .= mysqli_connect_error();
$msg .= " (" . mysqli_connect_errno() . ")";
exit($msg);
}
}
function confirm_result_set($result_set) {
if (!$result_set) {
exit("Database query failed.");
}
}
?>
答案 0 :(得分:0)
可能是因为:
$.ajax({
type: "POST",
url: "fetch.php",
data:'state_id='+val,
success: function(data){
$("#city").html(data);
}
});
据我所知,数据应该像这样传递:
data: {
'state_id': val
}
尝试在echo"TEST";
之后执行if(isset($_POST['state_id']))
以查看问题是否是您的jQuery或其他问题。