无限级分类的实现

该例子演示了无限级分类的显示和添加,只用一个数据表实现记录无限级分类,关键是每条记录都记录了上一层类别的ID(ParentId),然后通过一个递归函数来不断将类别显示出来。
 *大类1
  └二级小类1
    └三级小类1
      └四级小类1
        └五级小类1
 *大类2
   └二级小类2
*大类3

数据库说明:数据库db.mdb,classTable表的结构:
ClassId 类别ID(自动增长)
ParentId 父级ID 默认为0 (0代表最高级)
ClassName 类别名,
ClassDepth 是为了记录类别的级数
----------------------------------------------
| ClassId | ParentId | ClassName | ClassDepth |
----------------------------------------------
主要代码:
//先取出最高级(ParentId=0)的分类,程序代码
<
set conn=server.createobject("adodb.connection")
conn.open 
"Provider=Microsoft.Jet.Oledb.4.0;data source="&server.MapPath("db.mdb")
set Rs1=server.createobject("adodb.recordset"
Sql1
="select * from Classtable where ParentId=0 order by ClassId" 
Rs1.open Sql1,conn,
1,1 
if Rs1.eof or Rs1.bof then 
   response.write
"还没分类!" 
else 
   
while not Rs1.eof 
      id1
=Rs1("ClassId"
      name1
=Rs1("ClassName")
      response.write 
"*<a href='class.asp?id="&id1&"&name="&name1&"'>"&name1&"</a><br>"
      ParentId1
=Rs1("ParentId")
      
call ReClass(id1)
      Rs1.movenext 
   
wend 
end if 
Rs1.close 
set Rs1=nothing
%
> 

'递归调用函数,生成一个类别代码
sub ReClass(IntId) 
   
set Rs=server.createobject("adodb.recordset"
   Sql
="select * from classtable where ParentId="&IntId
   Rs.open Sql,conn,
1,1 
   i
=1
   
while not Rs.eof 
      id0
=Rs("ClassId"
      ClassName0
=Rs("ClassName"
      ParentId0
=Rs("ParentId"
      ClassDepth0
=Rs("ClassDepth")
      bRstr
=""
      
for j=1 to ClassDepth0
         bRstr
=" " & bRstr
      
next 
      response.write(bRstr 
& "└<a href='class.asp?id="&id0&"&name="& ClassName0&"'>"&ClassName0&"</a><br>")
      
call ReClass(id0) 
      Rs.movenext 
      i
=i+1
   
wend 
   Rs.close 
   
set Rs=nothing 
end sub

if request("a")="add" then
 
call add
end if
if request("name")<>"" then
%
>
<table width="80%" align="center" cellpadding="0" cellspacing="0">
<form action="class.asp?a=add&id=<%=request("id")%>" method="post">
   
<tr>
      
<td></td>
      
<td><font color="#FF0000"><%=request("name")%></font>添加小类</td>
   
</tr>
   
<tr>
      
<td>类别名:</td>
      
<td><input name="ClassName" type="text" id="ClassName"></td>
   
</tr>
   
<tr>
      
<td> </td>
      
<td><input type="submit" name="Submit" value="提交"></td>
   
</tr>
</form>
</table>
<%end if

sub add '添加类别
   id=request("id")
   ClassName
=request("ClassName")
   
set Rs=server.createobject("adodb.recordset")
   Rs.open 
"select ParentId,ClassDepth from classtable where ClassId="&id,conn,1,1
   ParentId
=Rs(0)
   ClassDepth
=Rs(1)+1
   Rs.close
   
set Rs=nothing
   Sql
="Insert INTO classtable (ClassName,ParentId,ClassDepth) values ('"&ClassName&"',"&id&","&ClassDepth&")"
   conn.execute Sql
   response.Write
"<script>alert('添加成功!');location.href='class.asp';</script>"
end sub
%
>

posted @ 2007-12-10 11:40  jay-c  阅读(502)  评论(1)    收藏  举报