参见下文,查看 不使用数据库 的 工作示例 。
使用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>使用父对象提供的数据来获取新事件
<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中,在之后
<select>,您需要给另一个
select加上
idas
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>'?>


