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();
}
