我想用php填充我的sql数据库中的下拉列表。
我创建了两个表:
CREATE TABLE IF NOT EXISTS `categories` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `subcategories` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`categoryID` INT(11) NOT NULL,
`subcategory_name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
创建一个config.php文件来存储数据库连接:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('dependent_list');
?>
创建index.php文件:
<?php
include('config.php');
$query_parent = mysql_query("SELECT * FROM categories") or die("Query failed: ".mysql_error());
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
</script>
</head>
<body>
<form method="get">
<label for="category">Parent Category</label>
<select name="parent_cat" id="parent_cat">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label>Sub Category</label>
<select name="sub_cat" id="sub_cat"></select>
</form>
</body>
</html>
现在创建一个loadsubcat.php文件:
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$query = mysql_query("SELECT * FROM subcategories WHERE categoryID = {$parent_cat}");
while($row = mysql_fetch_array($query)) {
echo "<option value='$row[id]'>$row[subcategory_name]</option>";
}
?>
到现在为止一切正常。
但是我想在链接上使用jquerymobile中的自定义选择菜单: http://demos.jquerymobile.com/1.4.5/selectmenu-custom/
为此我在index.php
中更改此代码<select name="parent_cat" id="parent_cat">
到:
<select name="parent_cat" id="parent_cat" data-native-menu="false" class="filterable-select" data-iconpos="left">
以及来自:
的子猫<select name="sub_cat" id="sub_cat"></select>
到:
<select name="sub_cat" id="sub_cat" data-native-menu="false" class="filterable-select" data-iconpos="left">
选择菜单项出现在弹出窗口中,不起作用,不会从数据库中提取数据。
任何帮助?
答案 0 :(得分:0)
您正在通过调用db call创建选择框,它会动态生成选项。在为其创建选项后,您需要在选择框上调用.selectmenu();
。尝试以下代码 -
$(document).ready(function() {
//apply custom select on parent category
$("#parent_cat").selectmenu();
$("#parent_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
//apply custom select on sub category
$("#sub_cat").selectmenu();
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
注意 - 以上解决方案假设您已经包含了自定义选择所需的jquery移动库。