用Ajax做的一棵無限級目錄樹

轉載:快樂笛子的博客(http://www.happyshow.org/view.php?id=107)

 

演示地址:http://www.happyshow.org/sample/20060918/ajax.html

使用了ajax,使原來非常繁瑣的無限級目錄樹變得簡單多了。並且由於是異步獲取節點數據,所以服務器的壓力比原來遍歷數據庫的方法小多了。
在這裏不得不提到css,通過定義

  • 的marging-left值,使樹中的父節點與子節點才錯位區分開來,實現簡單,並且編寫的js無需再考慮父子節點的錯位問題。
    本例中css還有一個大用處,當一個節點展開後又收縮,再點擊展開時,無需再讀取子節點數據,而是把收縮前的文檔結構重新顯示出來(display:block),這樣做既可以記憶用戶最後點擊的節點,又可以減少讀取數據的次數,又一次提了速度。

    本例目錄樹的文檔結構如下:
<div id="tree">
  <ul>
    <li>中國
      <ul>
             <li>廣東</li>
             <li>廣西</li>
             <li>湖南</li>
             <li>福建
             <ul>
                 <li>廈門</li>
             </ul>
         </li>
         </ul>
    </li>
  </ul>
</div>
一個節點級別用一個 ul 表示,因爲ul是塊級元素(默認樣式display==block),所以其與父節點的文字不在同一行顯示,又因爲ul有margin-left修飾,因此ul實現了換行又縮進的效果,即形成了子節點。

數據結構如下:

注意上圖中id與parentID的關係。

ajax通過訪問一個asp文件獲得數據,該asp文件程序如下:
<%@language=vbscript codepage=65001%>
<%
session.codepage = 65001
Response.CharSet = "utf-8"
response.contenttype="text/xml"
Response.expires=0
Response.AddHeader"pragma","no-cache"
Response.AddHeader"cache-control","no-store"
dim db
Set Conn=Server.CreateObject("ADODB.Connection")
db="data.mdb"
connstr ="Provider = Microsoft.Jet.OLEDB.4.0; Data Source ="& Server.MapPath(db)
Conn.Open connstr
 
 'response.write("<?xml version=""1.0"" encoding=""utf-8""?>"&Chr(13))
 Dim listid
 listid = Trim(request("id"))
 If listid = "" Then
  response.End()
 else
  
 Set rs = server.CreateObject("adodb.recordset")
 sql = "select * from [add] where parentID="&listid
 rs.open sql,conn,1,1
 if rs.eof or rs.bof then
  response.write("none&#33;&#33;&#33;")
 Else
  response.write("<area>")
  Do While Not rs.eof
   response.write("<address>"&rs("id")&"|"&rs("addname")&"|"&rs("url")&"</address>")
  rs.movenext
  Loop
  response.write("</area>")
 End If
 rs.close
 Set rs = nothing
 End if
%>
如果從瀏覽器上訪問此asp文件,結果是一個utf-8格式的標準的xml文件。
前臺頁面所有代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax 無限樹 by 快樂笛子([email protected])</title>
<style type="text/css">
*{ padding:0; margin:0}
body { font:12px "宋體"}
.tree { border:1px solid #ccc; margin:30px; width:200px; height:450px; float:left; padding:12px 12px 12px 0px}
.tree ul { margin-left:12px}
.tree li { list-style-type:none; margin:10px 0px; }
.tree li span { color:#FF0000; margin-left:4px}
.tree li a.close{ background:url(close.gif) no-repeat 1px 1px; width:11px; height:11px; font-size:1px; margin-right:4px; clear:left}
.tree li a.open{ background:url(open.gif) no-repeat 1px 1px; width:11px; height:11px; font-size:1px; margin-right:4px;clear:left}
.tree li a.nonedata{ background:url(nonedata.gif) no-repeat 1px 1px; width:11px; height:11px; font-size:1px; margin-right:4px;clear:left}
.tree li a { text-decoration:none; color:#000000; float:left}
textarea{ font-size:11px; font-family:Tahoma; width:300px; height:400px; line-height:18px; margin:30px; padding:2px}
</style>
<script type="text/javascript">

var xmlhttp;
//創建xmlhttp實例
function createxmlhttprequest(){
   try {
     xmlhttp = new XMLHttpRequest();
   } catch (trymicrosoft) {
     try {
       xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (othermicrosoft) {
       try {
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       } catch (failed) {
         xmlhttp = false;
       }  
     }
   }
      if (!xmlhttp)
     alert("創建 Ajax 實例出錯!");

}   
function delloadingtext(){
    if(innerPlace.tagName!="DIV"){
        innerPlace.getElementsByTagName("a")[1].innerHTML = innerPlace.getElementsByTagName("a")[1].innerHTML.substr(0,(innerPlace.getElementsByTagName("a")[1].innerHTML.length-loadingtext.length));
    }
    
}
var onsuccess = "";
var onloading = "";
var onerror = "";
var loadingtext = "<span>Loading...</span>"
var AjaxRequestObj = "";
//封裝 ajax 類
function Ajax(method,url,asynchronous,onsuccessFun,onloadingFun,onerrorFun){
    onsuccess = onsuccessFun;
    onloading = onloadingFun;
    onerror = onerrorFun
    this.asynchronous = true;
    this.onloading=function(){onloadFun};
    this.onerror=function(){onerrorFun};
    createxmlhttprequest();
    xmlhttp.onreadystatechange = handleStateChange;
    xmlhttp.open(method,url,asynchronous);
    this.request = function(){xmlhttp.send(null);}
}
function handleStateChange(){
    if (xmlhttp.readyState==4){
        if(xmlhttp.status==200){
            AjaxRequestObj = xmlhttp.responseXML;
            eval(onsuccess);
        }else{
            if(xmlhttp.status==404)
            eval(onerror); //頁面不存在
        }
    }else{ 
        if (xmlhttp.readyState==3)
            eval(onloading);
    }
}

var innerPlace="";
function innerloadingtext(obj){
    if(obj.parentNode.getElementsByTagName("a")[0].className=="open"){
        try{
            ulobj = obj.parentNode.getElementsByTagName("ul")[0];
        }catch(e){ulobj = "";}
        if(typeof(ulobj)!="object")
        obj.innerHTML += loadingtext;
    }
}
function switchclass(id,obj){  //改變li的樣式,從樣式判斷是否需要讀取數據
    if(obj.className=="close"){
        obj.className="open"; 
        try{
            ulobj = obj.parentNode.getElementsByTagName("ul")[0];
        }catch(e){ulobj = "";}
        if(typeof(ulobj)=="object"){
            if(ulobj.style.display="none"){
                ulobj.style.display="block";
            }else{
                getValue(id,obj.parentNode);
            }
        }else{
            getValue(id,obj.parentNode);
        }
    }else{
        if(obj.className=="open"){obj.className="close";obj.parentNode.getElementsByTagName("ul")[0].style.display="none";}
    }
}
function getValue(id,obj){ //取值
    var ajaxObj = new Ajax("GET","list.asp?id="+id,true,"getsuccess()","getting()","getfailed()");
    ajaxObj.request();
    innerPlace = obj;
}
function getsuccess(){  //取值成功後
    var addr = AjaxRequestObj.getElementsByTagName("address");
    var addrLen = addr.length;    
    if(addrLen==0){
        setTimeout("delloadingtext()",200)
        innerPlace.firstChild.className="nonedata";
    }else{
        var subnode="";
        var selfid;
        var name;
        var url;
        for (i=0; i<addrLen; i++){
          selfid = addr[i].firstChild.data.split("|")[0];
          name = addr[i].firstChild.data.split("|")[1];
          url = addr[i].firstChild.data.split("|")[2];
          if(url!="")
              subnode = subnode + "<li><a href='javascript:void(0)' onclick="switchclass("+ selfid +",this);innerloadingtext(this.parentNode.getElementsByTagName('a')[1])" class='close'> </a><a href='"+ url +"' target='mainFrame'  onclick="switchclass("+ selfid +",this.parentNode.getElementsByTagName('a')[0]);innerloadingtext(this)">" + name + "</a></li>";
          else
              subnode = subnode + "<li><a href='javascript:void(0)' onclick="switchclass("+ selfid +",this);innerloadingtext(this.parentNode.getElementsByTagName('a')[1])" class='close'> </a><a href='javascript:void(0)' onclick="switchclass("+ selfid +",this.parentNode.getElementsByTagName('a')[0]);innerloadingtext(this)">" + name + "</a></li>";
          
        }
        subnode = "<ul>" + subnode + "</ul>";
        setTimeout("delloadingtext()",200)
        innerPlace.innerHTML = innerPlace.innerHTML + subnode;
    document.getElementById("stru").value = document.getElementById("tree").innerHTML
    }
}
function getting(){ //正在取值時
//    innerPlace.innerHTML = "Loading...";
}
function getfailed(){ //取值失敗
    alert("err")
}
</script>
</head>

<body onload="getValue(0,document.getElementById('tree'))">

<h1 style=" margin:20px">Ajax無限級目錄樹:</h1>

<div class="tree" id="tree"></div>

<iframe src="" name="mainFrame" id="mainFrame" frameborder="1" style=" border:none; margin:30px; width:250px; height:400px; padding:0"></iframe>
<textarea id="stru"></textarea>
<div style="clear:both; text-align:center">Writen by misshjn (@ <a href="http://www.happyshow.org" target="_blank">http://www.happyshow.org</a>)</div>
</body>
</html>
演示示例是一個通過目錄樹控制iframe的例子。示例的右側是目錄樹的文檔結構代碼,每點擊一次節點,此代碼都會實時變化,可以把這些代碼存入cookie,這樣就可以保留目錄樹的狀態而不怕頁面被刷新了。當然body標籤的onload得變一變才行。但目錄樹的結構代碼字符量比較多,這個cookie一定比較大,so~,呵呵,還是沒有把保留狀態的功能做入示例中。

演示地址:http://www.happyshow.org/sample/20060918/ajax.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章