前台js:
var treeNodes;
$.ajax({
async: false,
cache: false,
type: 'POST',
contentType: "application/json",
url: "/MsgTypeTemItem/GetAllStr?temId=" + $("#temId").val(), //请求的action路径
error: function () {//请求失败处理函数
alert('请求失败');
},
success: function (data) { //请求成功后处理函数
data = "[" + data + "]";
treeNodes = eval(data);//格式化(object)数据
}
});
$.fn.zTree.init($("#treeDemo"), setting, treeNodes);
后台Controller:
public string GetAllStr()
{
string temId = Request.QueryString["temId"];
List<MsgTypeTemItem> allList = msgTypeItemService.GetAll();
string querySql = "select * from MessageTempletItem where TempletId='" + temId + "'";
DataTable dt = sqlHelper.GetDataTable(querySql);
string result = string.Empty;
foreach (DataRow dr in dt.Select("FatherId='0'"))
{
result += AppendJson(dr, dt);
}
int index = result.LastIndexOf("\r\n");
if (result.Length > )
result = result.Substring(, index - );
return result;
}
private static string AppendJson(DataRow dr, DataTable dtAll)
{
string parentNode = string.Empty;
string isTrue = "false";
parentNode = "{id:\'{id}\', pId:\'{pId}\', name:\'{name}\', open:" + isTrue + ", drag:true" + "},\r\n";
parentNode = parentNode.Replace("{id}", dr["ItemId"].ToString()).Replace("{pId}", dr["FatherId"].ToString()).Replace("{name}", dr["ItemContent"].ToString());
DataRow[] rows = dtAll.Select("FatherId='" + dr["ItemId"].ToString().Trim() + "'");
if(rows.Length!=)
{
foreach (DataRow row in rows)
{
parentNode += AppendJson(row, dtAll);
}
}
return parentNode;
}
注意:①.要后台数据进行eval(object化)--eval
eval前:[{id:'y1',pId:'',name:'y1',drag:true},{id:'y11',pId:'y1',name:'y11',drag:true},{id:'y2',pId:'',name:'y2',drag:true}]
eval后:[object Object],[object Object],[object Object]
相关知识点①:eval
var code1='"a" + 2'; //表达式 
var code2='{a:2}'; //语句 
var code3=[{a:1,b:2},{a:2,b:3}];
alert(eval(code1)); //->'a2' 
alert(eval(code2)); //->undefined 
alert(eval('(' + code2 + ')')); //->[object Object] 
alert(eval(code3));//->[object Object],[object Object] 
05-26 11:50