我是学习Ajax的新手,我使用PHP MYSQLI。我有2个选择标签,我想要第一个选择,在第二个选择标签中给出所选选项的子类别。例如,如果选择宝马提供与宝马有关的所有型号。我在这里写了代码,但我不知道为什么它不起作用。 2 select labels这是我的代码。
<script type="text/javascript">
function fetch_select(val)
{ $(function() {
$.ajax({
type: 'post',
url: 'ajax.php',
data: {
'get_option':val
},
success: function (response) {
$("#new_select").html(response);
}
});
});
}
</script>
这是主页:
<div class="row">
<div class="col-md-6">
<select id="select_box" class="form-control" onchange="fetch_select(this.value);">
<option disabled selected>1ci Kateqoriya</option>
<?php
$query = "SELECT * FROM categories WHERE parent_id IS NULL";
$select_box = $db->select($query);
?>
<?php while($row = $select_box->fetch_assoc()) : ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name_az']; ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="col-md-6">
<select id="new_select" class="form-control" >
<option disabled selected>2ci Kateqoriya</option>
</select>
</div>
</div>
这是ajax.php:
<?php
if(isset($_POST['get_option']))
{
$p_id = $_POST['get_option'];
$query = "SELECT * FROM categories WHERE parent_id ='$p_id'";
$ch_cat = $db->select($query);
while($row=$ch_cat->fetch_assoc())
{
echo "<option>".$row['name_az']."</option>";
}
exit;
}
?>
答案 0 :(得分:0)
我没有测试过代码,但我认为这应该可行。而不是仅通过ajax获取选项,而是像这样获取整个选择框。所以你的ajax.php将是 -
<?php
if(isset($_POST['get_option']))
{
$p_id = $_POST['get_option'];
$query = "SELECT * FROM categories WHERE parent_id ='$p_id'";
$ch_cat = $db->select($query);
echo "<select id='new_select' class='form-control' onchange=\"fetch_select2(this.value);\" > \n";
while($row=$ch_cat->fetch_assoc())
{
echo "<option>".$row['name_az']."</option>";
}
exit;
}
echo "</select>\n";
?>
主页:
<div class="row">
<div class="col-md-4">
<select id="select_box" class="form-control" onchange="fetch_select(this.value);">
<option disabled selected>1ci Kateqoriya</option>
<?php
$query = "SELECT * FROM categories WHERE parent_id IS NULL";
$select_box = $db->select($query);
?>
<?php while($row = $select_box->fetch_assoc()) : ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name_az']; ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="col-md-4" id="slect2" onchange="fetch_select2(this.value);">
<select id="new_select" class="form-control" >
<option disabled selected>2ci Kateqoriya</option>
</select>
</div>
<div class="col-md-4" id="slect3">
<select id="new_select2" class="form-control" >
<option disabled selected>2ci Kateqoriya</option>
</select>
</div>
</div>
和脚本:
<script type="text/javascript">
function fetch_select(val)
{ $(function() {
$.ajax({
type: 'post',
url: 'ajax.php',
data: {
'get_option':val
},
success: function (response) {
$("#select2").html(response);
}
});
});
}
function fetch_select2(val)
{ $(function() {
$.ajax({
type: 'post',
url: 'ajax2.php',
data: {
'get_option':val
},
success: function (response) {
$("#select3").html(response);
}
});
});
}
</script>