获取zTree选中节点
<body> <script type="text/javascript">
var setting = {
view: {
dblClickExpand: false,
showLine: true,
},
check: {
enable: true, //必选项
chkboxType: { "Y": "p", "N": "s" }, //Y被勾选,N没有勾选情况,p操作影响父节点,s影响子节点
},
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId:
}
},
callback: {
onCheck: onCheckNode //回调函数,获取选节点
} }; var zNodes = [
{ id: , pId: , name: "[excheck] 复/单选框功能 演示", open: true },
{ id: , pId: , name: "Checkbox 勾选操作", file: "excheck/checkbox" },
{ id: , pId: , name: "Checkbox nocheck 演示", file: "excheck/checkbox_nocheck" },
{ id: , pId: , name: "Checkbox chkDisabled 演示", file: "excheck/checkbox_chkDisabled" },
{ id: , pId: , name: "Checkbox halfCheck 演示", file: "excheck/checkbox_halfCheck" },
{ id: , pId: , name: "Checkbox 勾选统计", file: "excheck/checkbox_count" },
{ id: , pId: , name: "用 zTree 方法 勾选 Checkbox", file: "excheck/checkbox_fun" },
{ id: , pId: , name: "Radio 勾选操作", file: "excheck/radio" },
{ id: , pId: , name: "Radio nocheck 演示", file: "excheck/radio_nocheck" },
{ id: , pId: , name: "Radio chkDisabled 演示", file: "excheck/radio_chkDisabled" },
{ id: , pId: , name: "Radio halfCheck 演示", file: "excheck/radio_halfCheck" },
{ id: , pId: , name: "用 zTree 方法 勾选 Radio", file: "excheck/radio_fun" } ]; $(document).ready(function () {
var treenode = $.fn.zTree.init($("#treeDemo"), setting, zNodes); $('#didClick').click(function () {
$.ajax({
url: '/handler/ajax.ashx',
type: 'POST',
async: true,
data: {
PostMethod:"checkedBox",
nodesJson: chkNodeStr
},
dataType: 'json',
success: function (data) {
console.log(data)
},
error: function (xhr, textStatus) {
console.log(xhr)
console.log(textStatus)
},
});
});
});
var chkNodeArr;
var chkNodeStr="";
var nodeJson = [];
function onCheckNode() {
var treenode = $.fn.zTree.getZTreeObj("treeDemo");
chkNodeArr = treenode.getCheckedNodes(true); //true获取选中节点,false未选中节点,默认为true
for (var i = ; i < chkNodeArr.length; i++) {
nodeJson[i] = { "name": chkNodeArr[i].name, "id": chkNodeArr[i].id };
}
//console.log(chkNodeArr);
chkNodeStr = JSON.stringify(nodeJson);
} </script> <div>
<ul id="treeDemo" class="ztree"></ul> <button type="button" id="didClick">提交</button>
</div> </body>
后台解析json字符串,使用Newtonsoft
1,引用 using Newtonsoft.Json.Linq;
2,因为是数组所以用JArray解析,对象可以用JObject
if (method == "checkedBox") {
string jsonStr = context.Request["nodesJson"]; JArray ja = JArray.Parse(jsonStr);
Dictionary<string, string> dic = new Dictionary<string, string>(); foreach (JToken str in ja) {
dic.Add(str["name"].ToString(),str["id"].ToString());
} }
附上 zTree 官网 api 和 Newtonsoft.json 文档