JS文件如下:
var setting = {
async: {
// 異步加載
enable: true,
url: getUrl
},
callback: {
beforeExpand: beforeExpand,
onAsyncSuccess: onAsyncSuccess,
onAsyncError: onAsyncError
}
};
function createTree() {
$.ajax({
url: 'Handler.ashx?action=GetProvince', // url action是方法的名稱
data: { id: "0" },
type: 'POST',
dataType: "text", // 可以是text,如果用text,返回的結果為字符串;如果需要json格式的,可是設置為json
ContentType: "application/json; charset=utf-8",
success: function(data) {
$.fn.zTree.init($("#treeDemo"), setting, eval('(' + data + ')'));
},
error: function(msg) {
alert("數據加載失敗!");
}
});
}
function getUrl(treeId, treeNode) {
var param = "id=" + treeNode.id ;
return "Handler.ashx?action=GetProvince&" + param;
}
function beforeExpand(treeId, treeNode) {
if (!treeNode.isAjaxing) {
return true;
} else {
alert("zTree 正在下載數據中,請稍后展開節點。。。");
return false;
}
}
function onAsyncSuccess(event, treeId, treeNode, msg) {}
function onAsyncError() {
alert("數據加載失敗");
}
$(document).ready( function () {
createTree();
});
// 異步加載
enable: true,
url: getUrl
},
callback: {
beforeExpand: beforeExpand,
onAsyncSuccess: onAsyncSuccess,
onAsyncError: onAsyncError
}
};
function createTree() {
$.ajax({
url: 'Handler.ashx?action=GetProvince', // url action是方法的名稱
data: { id: "0" },
type: 'POST',
dataType: "text", // 可以是text,如果用text,返回的結果為字符串;如果需要json格式的,可是設置為json
ContentType: "application/json; charset=utf-8",
success: function(data) {
$.fn.zTree.init($("#treeDemo"), setting, eval('(' + data + ')'));
},
error: function(msg) {
alert("數據加載失敗!");
}
});
}
function getUrl(treeId, treeNode) {
var param = "id=" + treeNode.id ;
return "Handler.ashx?action=GetProvince&" + param;
}
function beforeExpand(treeId, treeNode) {
if (!treeNode.isAjaxing) {
return true;
} else {
alert("zTree 正在下載數據中,請稍后展開節點。。。");
return false;
}
}
function onAsyncSuccess(event, treeId, treeNode, msg) {}
function onAsyncError() {
alert("數據加載失敗");
}
$(document).ready( function () {
createTree();
});
Handler.ashx
<%@ WebHandler Language=
"
C#
" Class=
"
Handler
" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = " text/plain ";
string method = context.Request[ " action "];
switch (method)
{
case " GetModule ":
{
string parentID = context.Request.Params[ " id "]; // 參數為id
zTree zTree = new zTree();
context.Response.Write(zTree.GetModule());
break;
}
case " GetModule1 ":
{
string parentID = context.Request.Params[ " id "]; // 父節點id
zTree zTree = new zTree();
context.Response.Write(zTree.GetModule1(parentID));
break;
}
case " GetProvince ":
{
string[] para = context.Request.Params[ " id "].Split( ' , ');
string parentID = para[ 0]; // 父節點id
string areaCategory = "";
if (para.Length > 1)
{
areaCategory = para[ 1];
}
zTree zTree = new zTree();
context.Response.Write(zTree.GetProvince(parentID, areaCategory));
break;
}
default:
break;
}
}
public bool IsReusable {
get {
return false;
}
}
}
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = " text/plain ";
string method = context.Request[ " action "];
switch (method)
{
case " GetModule ":
{
string parentID = context.Request.Params[ " id "]; // 參數為id
zTree zTree = new zTree();
context.Response.Write(zTree.GetModule());
break;
}
case " GetModule1 ":
{
string parentID = context.Request.Params[ " id "]; // 父節點id
zTree zTree = new zTree();
context.Response.Write(zTree.GetModule1(parentID));
break;
}
case " GetProvince ":
{
string[] para = context.Request.Params[ " id "].Split( ' , ');
string parentID = para[ 0]; // 父節點id
string areaCategory = "";
if (para.Length > 1)
{
areaCategory = para[ 1];
}
zTree zTree = new zTree();
context.Response.Write(zTree.GetProvince(parentID, areaCategory));
break;
}
default:
break;
}
}
public bool IsReusable {
get {
return false;
}
}
}
CS文件
數據庫表為省市區三張表,網上到處都是,找找下載去吧。
public string GetProvince( string parentID, string areaCategory)
{
string treeJson = "";
string sql = "";
if (areaCategory.Trim() == " 省 ")
sql =
@" SELECT c.City Name, c.CityCode+','+'市' ID,c.ProvinceCode ParentID,CASE WHEN(SELECT COUNT(1) FROM Area a(nolock) WHERE c.CityCode =a.CityCode)>0 THEN 'true' ELSE 'false' END isParent FROM City c(nolock) WHERE c.ProvinceCode=' " +
parentID + " ' ";
else if (areaCategory.Trim() == " 市 ")
sql =
@" SELECT a.Area Name, a.AreaCode+','+'區' ID,a.CityCode ParentID,'false' isParent FROM Area a(nolock) WHERE a.CityCode=' " +
parentID + " ' ";
else
sql =
@" SELECT p.Province Name,p.ProvinceCode+','+'省' ID,'0' ParentID,CASE WHEN(SELECT COUNT(1) FROM City c(nolock) WHERE p.ProvinceCode =c.ProvinceCode)>0 THEN 'true' ELSE 'false' END isParent FROM Province p(nolock) ";
DataTable dt = Common.GetTable(sql);
if (dt.Rows.Count > 0)
{
treeJson = DtToJson1(dt, " ParentID ", parentID, " ID ", " Name ", " isParent ").Substring( 12);
}
return treeJson;
}
/// <summary>
/// 將DataTable轉為zTree的Json格式
/// </summary>
/// <param name="dt"> 要轉化的表 </param>
/// <param name="pField"> 表中的父節點字段 </param>
/// <param name="pValue"> 表中頂層節點的值,沒有 可以輸入為0 </param>
/// <param name="kField"> 關鍵字字段名稱 </param>
/// <param name="TextField"> 要顯示的文本 對應的字段 </param>
/// <param name="isParent"> 是否有子節點,主要通過sql實現 </param>
/// <returns></returns>
public static string DtToJson1(DataTable dt, string pField, string pValue, string kField, string TextField, string isParent)
{
StringBuilder sb = new StringBuilder();
string filter = String.Format( " {0}='{1}' ", pField, pValue); // 獲取頂級目錄.
DataRow[] drs = dt.Select(filter);
if (drs.Length < 1)
return "";
sb.Append( " ,\"children\":[ ");
foreach (DataRow dr in drs)
{
string pcv = dr[kField].ToString();
sb.Append( " { ");
sb.AppendFormat( " \"name\":\"{0}\", ", dr[TextField].ToString());
sb.AppendFormat( " \"id\":\"{0}\", ", dr[kField].ToString());
sb.AppendFormat( " \"isParent\":\"{0}\" ", dr[isParent].ToString());
sb.Append(DtToJson(dt, pField, pcv, kField, TextField).TrimEnd( ' , '));
sb.Append( " }, ");
}
if (sb.ToString().EndsWith( " , "))
{
sb.Remove(sb.Length - 1, 1);
}
sb.Append( " ] ");
return sb.ToString();
}