请参阅下文以查看不使用数据库的工作示例。
使用 MySQL 数据库的工作示例
如果您想使用数据库连接它,是的,这肯定是可能的。考虑这张表:
CREATE TABLE `contents` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR (255),
`parent` INT DEFAULT 0
);
INSERT INTO `contents` (`name`, `parent`) VALUES
('Names', 0),
('Places', 0),
('Animals', 0),
('Praveen', 1),
('Bill Gates', 1),
('Steve Jobs', 1),
('India', 2),
('New York', 2),
('London', 2),
('Singapore', 2),
('Cat', 3),
('Dog', 3),
('Tiger', 3),
('Deer', 3)
表结构
+----+------------+--------+
| id | name | parent |
+----+------------+--------+
| 1 | Names | 0 |
| 2 | Places | 0 |
| 3 | Animals | 0 |
| 4 | Praveen | 1 |
| 5 | Bill Gates | 1 |
| 6 | Steve Jobs | 1 |
| 7 | India | 2 |
| 8 | New York | 2 |
| 9 | London | 2 |
| 10 | Singapore | 2 |
| 11 | Cat | 3 |
| 12 | Dog | 3 |
| 13 | Tiger | 3 |
| 14 | Deer | 3 |
+----+------------+--------+
初始 HTML 和 PHP 代码
现在,让我们使用 PHP 首先填充初始值<select>
:
<?php
mysql_connect();
mysql_select_db("contents");
$result = mysql_query("SELECT * FROM `contents` WHERE `parent` = 0");
while(($data = mysql_fetch_array($result)) !== false)
echo '<option value="', $data['id'],'">', $data['name'],'</option>'
?>
现在<select>
准备好了。使用它的 onchange 函数,我们可以触发一个 AJAX 事件以<select>
使用 parent 提供的数据获取新的<select>
。
<select onchange="ajaxfunction(this.value)">
<!-- Options would have been initially populated here -->
</select>
现在对于 jQuery 函数,您可以这样做:
<script type="text/javascript">
function ajaxfunction(parent)
{
$.ajax({
url: 'process.php?parent=' + parent;
success: function(data) {
$("#sub").html(data);
}
});
}
</script>
在 HTML 中,在 之后,您需要用as<select>
给另一个。select
id
sub
<select onchange="ajaxfunction(this.value)">
<!-- Options would have been initially populated here -->
</select>
<select id="sub"></select>
处理 PHP 源代码
最后是源代码process.php
:
<?php
mysql_connect();
mysql_select_db("contents");
$result = mysql_query("SELECT * FROM `contents` WHERE `parent` = " . mysql_real_escape_string($_GET["parent"]));
while(($data = mysql_fetch_array($result)) !== false)
echo '<option value="', $data['id'],'">', $data['name'],'</option>'
?>
不使用数据库的工作示例
你只需要在 PHP 中替换它。
<?php
$parent = array("Name", "Place", "Animals");
foreach ($parent as $id => $name)
echo '<option value="s', $id,'">', $name,'</option>'
?>
对于process.php
:
<?php
$parent = array("Name", "Place", "Animals");
$s0 = array("Praveen", "Bill Gates", "Steve Jobs");
foreach (${$_GET["parent"]} as $id => $name)
echo '<option value="', $data['id'],'">', $data['name'],'</option>'
?>