我正在显示2个下拉列表。 html页面上的代码是
<head>
<script>
$(document).ready(function(){
$('#cat').change(function(){
var catid = $('#cat').val();
if(catid != 0)
{
$.ajax({
type:'post',
url:'fetchsubcat.php',
data:{id:catid},
cache:false,
success: function(returndata){
$('#subcat').html(returndata);
}
});
}
})
})
</script>
</head>
<body>
<fieldset>
<label>Category</label>
<select name="catname" id="cat">
<option value="0">Please Select a category</option>
<?php
require 'connection.php';
$sql = "SELECT * FROM category";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result))
{
$catname=$row["catname"];
$catid=$row["id"];
?>
<option value="<? echo $catname.'-'.$catid;?>"><? echo $catname;?></option>
<?}
}?>
</select>
</fieldset>
<fieldset>
<label>Subcategory</label>
<select name="subcatname" id="subcat">
<option></option>
</select>
</fieldset>
</body>
fetchsubcat.php页面上的代码是
<?php
require 'connection.php';
$sql = "SELECT * FROM subcategory where catid='".$_POST['id']."'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result))
{
$subcatname=$row["subcatname"];
$subcatid=$row["id"];
?>
<option value="<? echo $subcatname.'-'.$subcatid;?>"><? echo $subcatname;?></option>
类别表的视图
id catname
子类别表的视图
id catname catid subcatname
我希望当我选择类别时,第二个下拉列表应该只显示所选类别下的子类别,但问题是在选择类别时子类别下没有显示任何内容。任何人都可以帮助我
答案 0 :(得分:0)
您是否从AJAX结果中收到任何错误?我做了类似的事情,当我没有按预期得到结果时,我发现我需要向AJAX发送同步请求并强制浏览器等待返回的数据。
此外,使用已知的类别ID(例如)测试查询,将_POST['id']
替换为您知道的数据库中存在的与子类别相关联的数字。有了这个,应用程序是否按预期运行?
答案 1 :(得分:0)
试试这个..
<script>
$(document).ready(function(){
$('#cat').change(function(){
var catid = $('#cat').val();
if(catid != 0)
{
$.ajax({
type:'post',
url:'fetchsubcat.php',
data:{id:catid},
cache:false,
dataType: "json",
success: function(returndata){
$.each(returndata, function(i, item) {
$('#subcat').append('<option value="'+returndata[i].subcatname+'-'+returndata[i].subcatid+'">'+returndata[i].subcatname+'</option>');
});
}
});
}
})
})
</script>
在fetchsubcat.php
<?php
require 'connection.php';
$sql = "SELECT * FROM subcategory where catid='".$_POST['id']."'";
$result = mysqli_query($con, $sql);
$rows = Array();
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
print json_encode($rows);
?>
答案 2 :(得分:0)
将fetchsubcat.php的代码更改为
<?php
require 'connection.php';
$catid = $_REQUEST['id'];
$sql = "SELECT * FROM subcategory where catid='".$catid."'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$subcatname=$row["subcatname"];
$subcatid=$row["id"];
?>
<option value="<? echo $subcatname.'-'.$subcatid;?>"><? echo $subcatname;?></option>
<?}
}
else
{?>
<option value="">No sub category </option>
<?}?>