樹型菜單可以說是項目中應用最為廣泛的運用。以前無論使用微軟控制項的樹型,還是比較優秀的阿賴樹型,都是將資料全部讀出,然後再分級顯示。這樣如果資料量大,那麼第一次顯示將需要客戶等待很長一段時間,降低了客戶的體驗度。如今使用ajax,事情變得簡單了。
此運用參考了《征服web2.0開發技術詳解》的例子。
我使用的平台是struts+spring+hibernate,但與ajax打交道的也就是struts。我無法將整個代碼貼出來,因此把重要的前台ajax代碼貼出來,至於背景代碼就看你自己所使用的技術了。
1、jsp頁面
<% @ page language = " java " contentType = " text/html; charset=GB2312 " import = " java.util.*,com.wehave.oa.cecontract.model.TbJyhtflb " %>
< html >
< head >
< title > Insert title here </ title >
< link rel = " stylesheet " href = " ../css/tree.css " >
< script type = " text/javascript " src = " ../js/tree_ajax.js " ></ script >
< script type = " text/javascript " src = " ../js/tree_htfl.js " ></ script >
< script languge = " javascript " >
function ShowDetail(ID,NAME,FLAG) {
window.parent.right.location = " getContract.go?method=doGetContract&folderID= " + ID + " &&folderName= " + NAME + " &&flag= " + FLAG;
}
</ script >
</ head >
< body bgcolor = " #F6F9FF " >
< tbody >
< table cellpadding = " 0 " cellspacing = " 0 " width = " 300 " >
< div id = " load " style = " display:none " > < img src = " ../images/tree_loading.gif " > Loading data.. </ div >
< ul class = " tree " >
<% List treeList = (List)request.getAttribute( " treefolder " );
Iterator it = treeList.iterator();
while (it.hasNext()) {
out.println(it.next().toString());
}
%>
</ table >
</ tbody >
</ body >
</ html >
2、js代碼function showHide( id )
{
var el= document.getElementById( id );
var bExpand = true;
var images = el.getElementsByTagName("IMG");
if (images[0].src.indexOf("tree_minus.gif")!=-1)
{
bExpand = false;
images[0].src="../images/tree_plus.gif";
}else{
images[0].src="../images/tree_minus.gif";
}
var subs=el.lastChild;
if(bExpand)
subs.style.display="block";
else
subs.style.display="none";
}
function getSubTree( id ,submitURL)
{
var submitURL=submitURL
postXmlHttp( submitURL, 'parseSubTree("'+id+'")' ,'load("'+id+'")');
}
function parseSubTree(id)
{
var el= document.getElementById( id );
var ulElmt= document.createElement("UL");
ulElmt.innerHTML=_xmlHttpRequestObj.responseText;
el.appendChild(ulElmt);
var images = el.getElementsByTagName("IMG");
images[0].setAttribute("src", "../images/tree_minus.gif");
images[0].setAttribute("onclick", new Function("showHide('"+id+"')"));
var aTag = el.getElementsByTagName("A");
aTag[0].setAttribute("onclick", new Function("showHide('"+id+"')"));
var loadDiv= document.getElementById( "load" );
loadDiv.style.display="none";
}
function load(id)