我有一个树结构的SQL数据库;树有四层,所以树中的每个节点都在第1、2或3层,当然还有一个根节点在第0层。每个数据库条目都有字段title、parentname和level(0,1,2或3)。
我想在HTML表单中创建一系列最多三个下拉框。在开始的时候,页面应该只显示一个下拉框,只使用级别1上的Tree节点填充。选择其中一个应该会生成第二个下拉框,其中填充了所选节点的所有子节点(所有Level 1节点都有子节点)。然后,如果需要第三个下拉列表,那么选择其中一个应该具有相同的效果(大约一半的Level 2节点有子节点)。
我该怎么做呢?我是否需要使用PHP来生成所有关于更改事件的javascript ?
尝试测试这个脚本以确保它能够工作,然后您可以调整它。我不确定你是否需要反向工作。即在选择了第4级后,更改第1级。
index . php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script>
// get a dropdown based on the parentname and level
function getDropdown(parentname, level) {
var fields = {parentname: parentname, level: level}
var levelspan = $('span[level='+level+']');
// show it as loading first
levelspan.html('Loading...');
// use ajax to grab the next dropdown
// based on the parentname and level
$.get('ajax.php',fields,function(data){
// populare the appropriate span
// with the dropdown
levelspan.html(data);
});
}
// bind dropdowns on change
$('.selectDrop').live('change',function(){
var t = $(this);
// get the new parent and level
var newparent = $("option:selected",this).attr('name');
var level = t.attr('level');
getDropdown(newparent,level);
});
$(function(){
// load the first dropdown
getDropdown('initialparent',0);
});
</script>
<span level='0'></span>
<span level='1'></span>
<span level='2'></span>
<span level='3'></span>
ajax.php
<?php
// here you would have SQL query that
// grabs all the rows on $_GET['level']
// and where parentname is $_GET['parentname']
// then put them in an array called $rows
// where the key is the parentname and
// value is the title
// i'm using a static array for testing -
$rows = array('parent1'=>'asdf','parent2'=>'awegwe','parent3'=>'3ggwg');
// get the next level
$nextLevel = $_GET['level'] + 1;
echo "<select ";
// dont bind the 4th dropdown
if ($_GET['level'] < 3) {
echo "class='selectDrop' ";
}
echo "parentname='".$_GET['parentname']."' level='".$nextLevel."'>";
echo "<option name=''>- Level ".$nextLevel." -</option>";
foreach ($rows as $parentname => $title) {
echo "<option name='".$parentname."'>".$title."</option>";
}
echo "</select>";
?>