转载:快乐笛子的博客(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实现了换行又缩进的效果,即形成了子节点。
<ul>
<li>中国
<ul>
<li>广东</li>
<li>广西</li>
<li>湖南</li>
<li>福建
<ul>
<li>厦门</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
数据结构如下:
![](http://xinlingwuyu.iteye.com/attachments/month_0609/l200691902655.gif)
注意上图中id与parentID的关系。
ajax通过访问一个asp文件获得数据,该asp文件程序如下:
<
%@language=vbscript codepage=65001%>
<%
session.codepage = 65001
Response.CharSet = "utf-8"
response.contenttype="text/xml"
<%
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"
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!!!")
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
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!!!")
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 快乐笛子(misshjn@163.com)</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.οnerrοr=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)' οnclick="switchclass("+ selfid +",this);innerloadingtext(this.parentNode.getElementsByTagName('a')[1])" class='close'> </a><a href='"+ url +"' target='mainFrame' οnclick="switchclass("+ selfid +",this.parentNode.getElementsByTagName('a')[0]);innerloadingtext(this)">" + name + "</a></li>";
else
subnode = subnode + "<li><a href='javascript:void(0)' οnclick="switchclass("+ selfid +",this);innerloadingtext(this.parentNode.getElementsByTagName('a')[1])" class='close'> </a><a href='javascript:void(0)' οnclick="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 οnlοad="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~,呵呵,还是没有把保留状态的功能做入示例中。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax 无限树 by 快乐笛子(misshjn@163.com)</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.οnerrοr=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)' οnclick="switchclass("+ selfid +",this);innerloadingtext(this.parentNode.getElementsByTagName('a')[1])" class='close'> </a><a href='"+ url +"' target='mainFrame' οnclick="switchclass("+ selfid +",this.parentNode.getElementsByTagName('a')[0]);innerloadingtext(this)">" + name + "</a></li>";
else
subnode = subnode + "<li><a href='javascript:void(0)' οnclick="switchclass("+ selfid +",this);innerloadingtext(this.parentNode.getElementsByTagName('a')[1])" class='close'> </a><a href='javascript:void(0)' οnclick="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 οnlοad="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>
演示地址: http://www.happyshow.org/sample/20060918/ajax.html