---
title: "ajax + div +js +xml+ servlet 实现无限级动态目录树（原创）"
author: "streamfly"
date: "2007-05-11T16:20:11Z"
tags: []
slug: "ajax-div-js-xml-servlet"
draft: false
lastmod: "2007-05-11T16:20:11Z"
id: 78905
url: "https://streamfly.iteye.com/blog/78905"
---

虽然网上这方面的资料很多，但真正能用的几乎没有，而笔者最近在做开发的时候，实在找不到合适的。没办法，只好自己动手，丰衣足食了。。

这棵目录树,不仅实现了无限级动态目录.而且页面上可以通过右键菜单实现树节点的动态添加,删除和重命名.另外还支持节点之间的拖放操作.因为基于ajax技术,所以所有操作都是无刷新的.

缺点:因为时间紧迫,所以开发的时候,代码质量估计不是很高![](/javascripts/fckeditor/editor/images/smiley/msn/sad_smile.gif),另外,xml文件是一次性从数据库读取生成的,而不是随着节点的展开而读取数据,所以对于大数据量的访问是不适合的.

（真后悔啊， 花了n多时间，挂掉了n多脑细胞！！）。希望对大家有所帮助！！！

1。数据表结构

 

nodeid //节点id

nodename//节点名称

parentid//父节点id

childid //子节点id

 上面的字段类型都是varchar.根据项目了，设定为了11位

2.xml文件格式

noderoot id="" text="" parentid=""

node id="" text="" parentid=""

 xml 文件是从数据库里读取并由servlet动态生成的。除了根节点的 parentid 属性为空外，其他都是有数值的。

因为js是utf-8编码的，所以在servlet里面最好加上下面2句

response.setHeader("Cache-Control", "no-cache");  
  response.setContentType("text/xml;charset=utf-8");

3.ajax.js

js 代码

01. var req = new function()
02. {
03. this.xhr = null;
04. this.xmldata = null;
05. this.userid = null;
06. this.createInstance = function()
07. {
08. var instance = null;
09. try
10. {
11. instance = new ActiveXObject("Msxml2.XMLHTTP");
12. }
13. catch(e)
14. {
15. try
16. {
17. instance = new ActiveXObject("Microsoft.XMLHTTP");
18. }
19. catch(E)
20. {
21. instance = false;
22. }
23. }
24. if(!instance && typeof XMLHTTPRequest != 'undefined')
25. {
26. instance = new XMLHTTPRequest();
27. if (instance.overrideMimeType)
28. {
29. instance.overrideMimeType="text/xml";
30. }
31. }
32. return instance;
33. }
34. this.getxmldata= function()
35. {
36. this.userid = arguments\[0];
37. xhr = this.createInstance();
38. xhr.onreadystatechange=this.buildxmltree;
39. xhr.open("GET","/getdatafromXML?userid="+arguments\[0],true);
40. xhr.send(null);
41. }
42. this.buildxmltree = function()
43. {
44. if(xhr.readyState==4)
45. {
46. if(xhr.status==200)
47. {
48. req.xmldata = xhr.responseText;
49. var o = new ActiveXObject('Microsoft.XMLDOM');
50. o.async = false;
51. o.loadXML(req.xmldata);
52. req.doXMLMsg(o);
53. }
54. else
55. {
56. //deal the error here
57. }
58. }
59. }
60. this.doXMLMsg = function(obj)
61. {
62. treeview.data = obj;
63. treeview.xhr = req.xhr;
64. treeview.userid = req.userid;
65. treeview.init();
66. }
67. }

 

4.treeview.js

var treeview = new function() {  
 this.data = null;  
 this.xhr = null;  
 this.userid = null;  
 this.icon=new Array();  
 this.icon\["leaf"]='/Doc/images/child.gif';  
this.icon\["open"]='/Doc/images/opened.gif';  
 this.icon\["close"]='/Doc/images/closed.gif';  
 this.user = null;  
 this.rootid = null;  
 this.root = null;  
 this.dragElement = null;  
 this.currElement = null;  
 this.dragid = null;  
 this.targetid = null;  
 this.rightmenu = null;  
 this.dragPath = null;  
 this.jink = "no";  
   
 this.init = function() {  
  this.user = this.data.getElementsByTagName("noderoot")\[0].getAttribute("text");  
  this.rootid = this.data.getElementsByTagName("noderoot")\[0].getAttribute("id");  
 this.root = document.createElement("div");  
  this.root.roll = 0;  
  this.root.style.position="relative";  
 this.root.style.display="block";  
 this.root.innerHTML="";  
  this.root.innerHTML+='![](+#%23this.icon%5B)';  
  this.root.innerHTML+=''+this.user+'';  
  this.root.ondragstart=treeview.dragstart;  
  this.root.ondragover=treeview.dragover;  
  this.root.ondrop=treeview.drop;  
  this.root.ondragend=treeview.dragend;  
  this.root.onmousedown=treeview.selectText;  
  document.body.appendChild(this.root);

 this.rightmenu = document.createElement("div");  
  this.rightmenu.id = "menu";  
  this.rightmenu.style.position="absolute";  
  this.rightmenu.style.width="30px";  
 this.rightmenu.style.height="60px";  
  this.rightmenu.style.display="none";  
  document.body.appendChild(this.rightmenu);  
    
     var obj = this.data.documentElement;  
    if(obj.hasChildNodes()) {  
  var i;  
  var nodes = obj.childNodes;  
   for(i=0;i #    var el = document.createElement("div");  
    el.innerHTML="";  
   var subObj = nodes.item(i);  
    var subid = subObj.getAttribute("id");  
    el.roll = 0;  
   el.style.position="relative";  
    el.style.marginLeft="14px";  
   el.style.display="none";  
   if(subObj.hasChildNodes()) {  
    el.innerHTML+='![](+#%23treeview.icon%5B)';  
   el.innerHTML+=''+subObj.getAttribute("text")+'';  
       this.root.appendChild(el);  
     this.showChilds(subObj,el);  
    }else {  
    el.innerHTML+='![](+#%23treeview.icon%5B)';  
     el.innerHTML+=''+subObj.getAttribute("text")+'';  
     this.root.appendChild(el);  
    }  
  }  
  }            
 }

 this.showChilds=function(o,ev)  
 {  
  var i;  
  var nodes = o.childNodes;  
  for(i=0;i #  {   
   var el = document.createElement("div");  
   el.innerHTML="";  
   var subObj = nodes.item(i);  
   var subid = subObj.getAttribute("id");  
   el.roll = 0;  
   el.style.position="relative";  
   el.style.marginLeft="14px";  
   el.style.display="none";  
   if(subObj.hasChildNodes())   
   {  
    el.innerHTML+='![](+#%23treeview.icon%5B)';  
    el.innerHTML+=''+subObj.getAttribute("text")+'';  
       ev.appendChild(el);  
                this.showChilds(subObj,el);  
  }else   
   {  
    el.innerHTML+='![](+#%23treeview.icon%5B)';  
   el.innerHTML+=''+subObj.getAttribute("text")+'';  
    ev.appendChild(el);  
  }  
  }  
}

 this.addElement= function(id) {  
  var obj = document.getElementById(id);  
  var upObj = obj.parentNode;  
  var o = arguments\[1];  
  if(o) {  
   var subObj=o.childNodes.item(1);           
        subObj.setAttribute("parentid",id);  
   upObj.appendChild(o);     
   if(upObj.getAttribute("roll")==0)   
   {  
    upObj.childNodes.item(0).setAttribute("src",treeview.icon\["open"]);  
  }   
         var subid = subObj.getAttribute("id");  
      xhr.open("GET","/addElement?parentid="+id+"&nodeid="+subObj.getAttribute("id")+"&nodename="+subObj.getAttribute("name")+"&path="+treeview.getfullpath(subObj.getAttribute("id"),""));  
     xhr.send(null);  
      return;  
  }   
 }  
   
 this.deleteElement=function(valueid) {  
  menu.style.display="none";  
 var delPath = treeview.getfullpath(valueid,"");  
  var obj = document.getElementById(valueid);  
  var parentid = obj.getAttribute("parentid");  
  var upObj = document.getElementById(parentid);  
  var oEle = obj.parentNode.getElementsByTagName("div");  
 if(oEle.length!=0)  
  {  
   var i;  
   for(i=0;i #   {  
    var subObj = oEle.item(i);  
   if(subObj.parentNode==obj.parentNode)  
   {  
     this.deleteChilds(subObj);  
     obj.parentNode.removeChild(subObj);  
   }  
   }   
 }  
  upObj.parentNode.removeChild(obj.parentNode);  
  oEle = upObj.parentNode.getElementsByTagName("DIV");  
  var bool = upObj.parentNode.childNodes.item(1).getAttribute("parentid");  
  if(oEle.length==0)  
  {  
   if((bool!="")&&(bool!=null)) {  
    upObj.parentNode.childNodes.item(0).setAttribute("src",treeview.icon\["leaf"]);  
       upObj.parentNode.setAttribute("roll",0);  
  }  
  }  
 xhr.open("GET","/delElement?id="+valueid+"&parentid="+parentid+"&subPath="+delPath);  
  xhr.send(null);   
    
 }  
   
 this.deleteChilds=function(o) {  
  var oEle = o.getElementsByTagName("DIV");  
  if(oEle.length!=0)  
  {  
   var i;  
   for(i=0;i #   {  
    var subObj = oEle.item(i);  
    if(subObj.parentNode==o)  
    {  
    this.deleteChilds(subObj);  
     o.removeChild(subObj);  
   }  
   }  
  }   
 }  
   
 this.rename=function(nameid) {  
  menu.style.display="none";  
  var path = treeview.getfullpath(nameid,"");  
  var obj = document.getElementById(nameid);  
 var result = prompt("please input a new name","");  
  if(result!=null) {  
   obj.setAttribute("name",result);  
   obj.innerText=result;  
  }  
  xhr.open("GET","/rename?name="+result+"&nameid="+nameid+"&path="+path+"&upPath="+treeview.getfullpath(obj.getAttribute("parentid"),""));  
  xhr.send(null);  
 }  
   
 this.selectText=function()   
 {  
  var o = window.event.srcElement;  
  if(o.tagName!="SPAN") {  
   return;  
  }  
 var ra = document.body.createTextRange();     
        ra.moveToElementText(o);   
        ra.select();       
        window.event.cancelBubble = true;  
 }  
   
 this.dragstart=function()   
 {  
  var o = window.event.srcElement;  
 if(o.tagName != "SPAN")   
  {  
   return false;  
  }  
 this.dragid = o.getAttribute("id");  
  this.dragPath = treeview.getfullpath(this.dragid,"");  
 this.dragElement = o.parentNode;  
  var length = treeview.childNodeNum(this.dragElement.parentNode);  
  if(length==1)  
  {  
   this.dragElement.parentNode.childNodes.item(0).setAttribute("src",treeview.icon\["leaf"]);  
  }  
 }  
   
 this.dragover=function() {  
  if(!this.dragElement.contains(window.event.srcElement)) {  
   if(window.event.srcElement.tagName=="DIV")  
  {  
    this.currElement = window.event.srcElement;  
   }  
   else  
   {  
    this.currElement = window.event.srcElement.parentNode;  
  }  
            window.event.returnValue = false;  
  }  
 }  
   
 this.drop=function() {  
  this.targetid = this.currElement.childNodes.item(1).getAttribute("id");  
  this.currElement.appendChild(this.dragElement);  
  this.dragElement.childNodes.item(1).setAttribute("parentid",this.currElement.childNodes.item(1).getAttribute("id"));  
 }  
   
 this.dragend=function() {  
  var length = treeview.childNodeNum(this.currElement);  
  if(length!=0)  
  {  
   this.currElement.childNodes.item(0).setAttribute("src",treeview.icon\["open"]);  
   this.currElement.setAttribute("roll",0);  
  }  
  xhr.open("GET","/dragElement?dragid="+this.dragid+"&targetid="+this.targetid+"&dragPath="+this.dragPath+"&targetPath="+treeview.getfullpath(this.dragid,""));  
  xhr.send(null);  
 }  
   
 this.showDiv=function() {  
  var o = window.event.srcElement;  
  if(o.tagName!="SPAN") {  
   if(o.tagName=="IMG") {  
    o = o.parentNode.item(1);  
   }else {  
    o = o.item(1);  
   }  
  }  
  var id = o.getAttribute("id");  
  treeview.rightmenu.style.left=event.clientX;  
  treeview.rightmenu.style.top=event.clientY;   
    
  var parent = o.getAttribute("parentid");

//这里的那段代码总是显示不出来，看源代码吧！

 this.getfullpath=function(nodeid,path) {//get the full path of the node  
  var path = path;  
  var node = document.getElementById(nodeid);  
  path = "/"+node.getAttribute("name")+path;    
  var parentid = node.getAttribute("parentid");  
  if(parentid!=null&&parentid!="") {  
   path = this.getfullpath(parentid,path);  
  }  
  return path;  
 }  
   
 this.jinkpage=function() {  
  var jink = arguments\[0];  
  var o = window.event.srcElement;  
  if(o.tagName=="div") {  
   o = o.childNodes.item(1);  
  }else if(o.tagName=="img") {  
   o = o.parentNode.childNodes.item(1);  
  }  
  var id = o.getAttribute("id");  
  var pathway = treeview.getfullpath(id,"");  
  if(jink=="no") {  
   pathway = "abcdef";  
  }  
  parent.frames\["right"].location.href="/Doc/jsp/showAllFileMsg.jsp?path="+pathway;  
 }  
   
 this.buildObj=function() {  
  menu.style.display="none";  
  var o = new Object();  
  var id = this.userid.toString()+this.getRandomNumber();  
  var result = prompt("please input a new name","");  
  if(!result) {  
   alert("the name can\`t be null!!");  
   result = prompt("please input a new name","");  
  }   
  

js 代码

1. o = document.createElement("div");
2. o.roll = 0;
3. o.style.position="relative";
4. o.style.marginLeft="10px";
5. o.style.padding = "2px";
6. o.style.display="block";
7. o.innerHTML='"treeview.divCtrl()" /&gt;';
8. o.innerHTML+='"cursor:hand;height:20px" id='+id+' name='+result+' parentid=""'+' onClick="treeview.jinkpage()" oncontextmenu="treeview.showDiv();return false"&gt;'+result+'';
9. return o;

   
 this.getRandomNumber=function() {  
  var num = Math.round(10000\*Math.random());  
  return num;  
 }  
   
 this.divCtrl=function()  
 {  
  var o = window.event.srcElement;  
  var img = o.getAttribute("src");  
  img = img.substring(img.lastIndexOf("/")+1);  
  if(img=="child.gif")  
  {  
   return;  
  }  
  var obj = o.parentNode;  
  if(obj.getAttribute("roll")==0)  
  {  
   var oEle = obj.getElementsByTagName("div");  
   if(oEle.length!=0)  
   {  
    var i;  
    for(i=0;i     {  
     var subObj = oEle.item(i);  
     if(subObj.parentNode==obj)  
     {  
      subObj.style.display="block";  
     }  
    }  
   }  
   o.setAttribute("src",treeview.icon\["open"]);  
   obj.setAttribute("roll",1);  
  }    
  else if(obj.getAttribute("roll")==1)  
  {  
   var oEle = obj.getElementsByTagName("div");  
   if(oEle.length!=0)  
   {  
    var i;  
    for(i=0;i     {  
     var subObj = oEle.item(i);  
     if(subObj.parentNode==obj)  
     {   
      if(subObj.getAttribute("roll")==1)  
      {  
       this.hideDiv(subObj);  
      }  
      subObj.style.display="none";   
     }   
    }  
   }  
   o.setAttribute("src",treeview.icon\["close"]);  
   obj.setAttribute("roll",0);  
  }    
 }  
   
 this.hideDiv=function(o)  
 {  
  var oEle = o.getElementsByTagName("div");  
  if(oEle.length!=0)  
  {  
   var i;  
   for(i=0;i    {  
    var subObj = oEle.item(i);  
    if(subObj.parentNode==o)  
    {   
     if(subObj.getAttribute("roll")==1)  
     {  
      this.hideDiv(subObj);  
     }  
     subObj.style.display="none";   
    }   
   }  
  }  
  o.childNodes.item(0).setAttribute("src",treeview.icon\["close"]);  
  o.setAttribute("roll",0);  
 }  
   
 this.hidemenu=function()  
 {  
  menu.style.display="none";  
 }  
   
 this.childNodeNum=function(o)  
 {  
  var oEle = o.getElementsByTagName("DIV");  
  return oEle.length;  
 }  
   
}

5。showTree.jsp

java 代码

01. "Content-Type" content="text/html; charset=utf-8"&gt;
02. "stylesheet" type="text/css" href="/Doc/css/panel.css"&gt;
03. &lt;script type=&lt; span=""&gt;"text/javascript" src="/Doc/js/treeview.js" charset="utf-8"&gt;&lt;/script&gt;
04. &lt;script type=&lt; span=""&gt;"text/javascript" src="/Doc/js/ajax.js" charset="utf-8"&gt;&lt;/script&gt;
05. "treeview.hidemenu()" class="blue"&gt;
06. &lt;script language=&lt; span=""&gt;"javascript"&gt;
07. var renamefolder = "重命名文件夹";
08. var makefolder = "新建文件夹";
09. var delfolder = "删除文件夹";
10. req.getxmldata(&lt;%= userid %&gt;);
11. &lt;/script&gt;

 

//晕啊，这什么编辑器啊，上传个文件都有bug！！！删除多余的删了n年也没反应！！！