|
我做某个项目时,有需求的是做一个动态的无限级的联动菜单。由于本人比较懒于是上网找找有关的代码,但很多都没有满足需求,其中有一编文章是用JavaScript对XML文件操作来实现无限级联动菜单的,我们可结合ASP来完成对数据库值的读取,然后写入XML文件,再用JavaScript读出来并且控制它的联动。 这儿的关键是把数据库内的N层数据类读出来然后正确写入XML文件中: 我的数据库表结构是这样的: 'tbl_Class 列名 数据类型 长度 说明 ClassID int 4 类ID ModuleID int 4 模块ID GroupID int 2 标识一个组 ClassName nvarchar 50 类别名称 ParentID int 2 连接到组(0表示是父类)
'####################################我的ASP代码如下#################################### '我把连接数据库的代码忽略。
'函数名字:OpenXml(FileName) '入口参数: filename 需要连接或打开的xml文件名 '返回值 :XmlDoc就是一个成功装载XML文档的对象了。 ' 有错误则打印错误信息strError '------------------------------------------------
function OpenXml(filename) dim strSourceFile ,XmlDoc,strError strSourceFile = filename Set XmlDoc = Server.CreateObject("Microsoft.XMLDOM") '创建XMLDOM实例 XmlDoc.async = false XmlDoc.load(strSourceFile) OpenXml=XmlDoc.parseerror.errorcode if XmlDoc.parseerror.errorcode<>0 then strError="<h2>error"&XmlDoc.parseerror.errorcode&"</h2>" strError=strError&XmlDoc.parseerror.reason&"<br>" strError=strError&XmlDoc.parseerror.url&"<br>" strError=strError&XmlDoc.parseerror.line&"<br>" strError=strError&XmlDoc.parseerror.filepos&"<br>" strError=strError&XmlDoc.parseerror.srcText&"<br>" response.write strError '输出错误 else set OpenXml=XmlDoc '返回实例 end if end function
'------------------------------------------------ '函数名字:CloseXml() '参数: XmlDoc XML组件实例 '------------------------------------------------ function CloseXml(XmlDoc) if IsObject(XmlDoc) then set XmlDoc=nothing end if end function
'------------------------------------------------ '函数名字:SelectXmlNode '参数:XmlDoc XML组件实例 ' e 元素的名字 '返回元素实例 '------------------------------------------------ function SelectXmlNode(XmlDoc,e) dim n
set n=XmlDoc.selectSingleNode("//" & e ) set selectXmlNode= n
end function
Dim n,np,MaxGroup,root,xmlDoc,nt,filename,s,ss,TorF filename=server.mappath("demo.xml") set xmlDoc=openXML(filename)'打开XML RemoveAllNodes xmlDoc,"Root"'把Root和它下面的子项清除,这样可以多次方便读写 set root= xmlDoc.createElement("Root") xmlDoc.appendChild root'创建一个顶层元素 sql="select Max(GroupID) from tbl_Class " '读出最大的层次 set rs=cn.execute(sql) if isnull(rs(0)) then MaxGroup=0 else MaxGroup=rs(0) '如果为null 表示没有数据 s="":ss="" set nt=xmldoc.createElement("item") nt.setAttribute "text", "请选择" root.appendChild nt '创建一个元素 for i=1 to MaxGroup '开始循环 sql="select * from tbl_Class where GroupID=" & i '由底层向顶层读取 set rs=cn.execute(sql) TorF=False '为了每一个层上都创建一个“请选择”的空取。 do while rs.eof =false '开始读取下层的数据 Set n = xmlDoc.createElement("item" & rs("ClassID")) '创建一个命名为item + ID号的标记元素 n.setAttribute "text",rs("ClassName")'把它的属性“text”设置为数据库表内的
ClassName n.setAttribute "value",rs("ClassID")'把它的属性“value”设置为数据库表内的
ClassID if rs("ParentID")>0 then '是有上层数据的 set np=selectXmlNode(xmlDoc,"item" & rs("ParentID")) '把它的上层数据元素先读出保存在np if TorF=false the 此新闻共有3页 上一页 1 2 3 下一页 |