使用jQuery和asp.net将Json字符串构建到树视图

我使用asp.net和ajax生成Json数据。

当我尝试使用下面的代码绘制树时,它不起作用另一方面代码2部分工作时,我把它作为静态

注意:使用库treant.js

链接: http : //fperucic.github.io/treant-js/

代码1:

$(function () { $.ajax({ type: "POST", url: "Default.aspx/Hello", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var Details = data.d; if (Details != "") { var tree_design = ''; //sessionStorage.setItem("str_data", tree_design); var currDepth = 0; var totalData = $.map(Details, function (n, i) { return i; }).length; var lastNodeIndex = parseInt(totalData) - 2; //-----------------------------------------// $.each(Details, function (index, item) { if (Details[parseInt(index) + 1] === undefined || Details[parseInt(index) + 1] == null || Details[parseInt(index) + 1] == "") { //alert("undefined"); } else { //console.log(index); //console.log(item.Name); //console.log(item.Depth); //alert(item.Depth); //console.log(item.Lft); //-----------------------------------// // Level down? (or the first) if (((parseInt(item.Depth) > parseInt(currDepth)) || parseInt(index) == 0) && parseInt(item.Depth) != 0) { tree_design += 'children: ['; } //----------------------------------// // Level up? if (parseInt(item.Depth) < parseInt(currDepth)) { tree_design += '' + '}],'.repeat(parseInt(currDepth) - parseInt(item.Depth)); } //----------------------------------// if (parseInt(item.Depth) != 0) { tree_design += '{ connectors: { style: { stroke: "#000000" } },'; } //---------Print Node Text-------------// tree_design += 'text: { name: "' + item.Name + '" },HTMLclass: "blue",image: "images/no_member.png",'; //---------------------------------------// //console.log(Details[parseInt(index) + 1].Depth); var nextEleDepth = Details[parseInt(index) + 1].Depth; //console.log(nextEleDepth); // Check if there's chidren if (parseInt(index) != lastNodeIndex && (parseInt(nextEleDepth) <= parseInt(item.Depth))) { tree_design += '},'; // If not, close the 
  • } //---------------------------------------// // Adjust current depth currDepth = parseInt(item.Depth); //---------------------------------------// //console.log(parseInt(index)+"=="+lastNodeIndex); // Are we finished? if (parseInt(index) == lastNodeIndex) { //console.log("Are we finished"); tree_design += '' + '}],'.repeat(currDepth); } //------------------------------------// } }); //------------------Draw Tree---------------------------// //console.log(tree_design); var chart_config = { chart: { container: "#basic-example", nodeAlign: "BOTTOM", connectors: { type: "step" }, node: { HTMLclass: "nodeExample1" } }, nodeStructure: { tree_design } }; //console.log(tree_design); new Treant(chart_config); //-------------------------------------------------------// } } }); });
  • 代码2:工作

      $(function () { $.ajax({ type: "POST", url: "Default.aspx/Hello", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var Details = data.d; if (Details != "") { var tree_design = ''; //sessionStorage.setItem("str_data", tree_design); var currDepth = 0; var totalData = $.map(Details, function (n, i) { return i; }).length; var lastNodeIndex = parseInt(totalData) - 2; //-----------------------------------------// $.each(Details, function (index, item) { if (Details[parseInt(index) + 1] === undefined || Details[parseInt(index) + 1] == null || Details[parseInt(index) + 1] == "") { //alert("undefined"); } else { //console.log(index); //console.log(item.Name); //console.log(item.Depth); //alert(item.Depth); //console.log(item.Lft); //-----------------------------------// // Level down? (or the first) if (((parseInt(item.Depth) > parseInt(currDepth)) || parseInt(index) == 0) && parseInt(item.Depth) != 0) { tree_design += 'children: ['; } //----------------------------------// // Level up? if (parseInt(item.Depth) < parseInt(currDepth)) { tree_design += '' + '}],'.repeat(parseInt(currDepth) - parseInt(item.Depth)); } //----------------------------------// if (parseInt(item.Depth) != 0) { tree_design += '{ connectors: { style: { stroke: "#000000" } },'; } //---------Print Node Text-------------// tree_design += 'text: { name: "' + item.Name + '" },HTMLclass: "blue",image: "images/no_member.png",'; //---------------------------------------// //console.log(Details[parseInt(index) + 1].Depth); var nextEleDepth = Details[parseInt(index) + 1].Depth; //console.log(nextEleDepth); // Check if there's chidren if (parseInt(index) != lastNodeIndex && (parseInt(nextEleDepth) <= parseInt(item.Depth))) { tree_design += '},'; // If not, close the 
  • } //---------------------------------------// // Adjust current depth currDepth = parseInt(item.Depth); //---------------------------------------// //console.log(parseInt(index)+"=="+lastNodeIndex); // Are we finished? if (parseInt(index) == lastNodeIndex) { //console.log("Are we finished"); tree_design += '' + '}],'.repeat(currDepth); } //------------------------------------// } }); //------------------Draw Tree---------------------------// //console.log(tree_design); var chart_config = { chart: { container: "#basic-example", nodeAlign: "BOTTOM", connectors: { type: "step" }, node: { HTMLclass: "nodeExample1" } }, nodeStructure: { text: { name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}] } }; //console.log(tree_design); new Treant(chart_config); //-------------------------------------------------------// } } }); });
  • 代码3:服务器脚本(ASP.Net C#)

     using CDB.System.Common.Layout.Company; using PRP.PPL.System.include.config.connection; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; namespace PPL.Data.HRD.Organogram.Tree1 { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static Details[] Hello() { string sql; db_ppl Connstring = new db_ppl(); sql = @"SELECT node.category_id, node.name, COUNT(parent.category_id) - 1 AS depth, node.lft, node.rgt FROM nested_category AS node CROSS JOIN nested_category AS parent WHERE (node.lft BETWEEN parent.lft AND parent.rgt) GROUP BY node.category_id, node.name, node.lft, node.rgt ORDER BY node.lft"; List
    details_data = new List
    (); using (SqlConnection con = Connstring.getcon) { using (SqlCommand cmd = new SqlCommand(sql, con)) { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Details col_data = new Details(); col_data.category_id = reader.GetInt32(0); col_data.Name = reader.GetString(1); col_data.Depth = reader.GetInt32(2); col_data.Lft = reader.GetInt32(3); col_data.Rgt = reader.GetInt32(4); details_data.Add(col_data); } } } return details_data.ToArray(); } //---------------For Details Data----------------// public class Details { public Int32 category_id { get; set; } public string Name { get; set; } public Int32 Depth { get; set; } public Int32 Lft { get; set; } public Int32 Rgt { get; set; } } } }

    代码4:asp.Net部分

          #basic-example { overflow: unset !important; }       

    Book Progress

    输出: 在此处输入图像描述

     var tree_design='text: { name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}]'; nodeStructure: { tree_design } 

    当你在nodeStructure中链接tree_design时,它是字符串格式,但是nodeStructure期望以json格式转换为json中的tree_design或者这样做

     var tree_design='{ name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Director)" },HTMLclass: "blue",image: "images/no_member.png",}]'; nodeStructure: { text: tree_design } 

    我现在在PHP代码中有解决方案,我想通过使用Ajax和jQuery将其转换为asp.net

      node.rgt ORDER BY t2.rgt-node.rgt ASC LIMIT 1 ),0) AS parent_id FROM `nested_category` AS node CROSS JOIN `nested_category` AS parent WHERE node.`lft` BETWEEN parent.`lft` AND parent.`rgt` GROUP BY node.`name` ORDER BY node.`lft`"; $qry_tree = mysqli_query($con,$sql_tree); $array_parent_data = array(); // Build array $tree = array(); while($fetch_tree=$qry_tree->fetch_assoc()) { $tree[] = $fetch_tree; } // Bootstrap loop $tree_design = ''; $currDepth = 0; $lastNodeIndex = count($tree) - 1; $parent_id=""; // Start the loop foreach ($tree as $index => $currNode) { $lr_distance=$currNode['rgt']-$currNode['lft']; $sql_path_height="SELECT * FROM `tree_details` WHERE `tree_id`=".$currNode['category_id']; $qry_path_height = mysqli_query($con,$sql_path_height); $fetch_path_height=$qry_path_height->fetch_assoc(); $path_height=$fetch_path_height['level_height']; $path_height=($path_height=="")?0:$path_height; $level_change=($path_height/10); //-----------------------------------// // Level down? (or the first) //if (($currNode['depth'] > $currDepth || $index == 0) && $currNode['depth']!=0) { if (($currNode['depth'] > $currDepth) && $currNode['depth']!=0) { $tree_design .= 'children: ['; } // Level up? if ($currNode['depth'] < $currDepth) { $tree_design .= str_repeat(']},', $currDepth - $currNode['depth']); } // Always open a node $t = ($index == 0) ? 1 : 2; if($currNode['depth']!=0) { $tree_design .= '{ connectors: { style: { stroke: "#000000" } },'; } //--------------For Leaf--------------// if($path_height>0 && $lr_distance==1) { for($i=0;$i<$level_change;$i++) { $tree_design.='pseudo: true, connectors: { style: { stroke: "#000000" } }, children: [ {'; } } //-----------For Parent---------------// if($path_height>0 && $lr_distance>1) //if($lr_distance>1) { $sql_all_child="SELECT * FROM `nested_category` WHERE `lft`>".$currNode['lft']." AND `rgt`<".$currNode['rgt']; $qry_all_child = mysqli_query($con,$sql_all_child); $all_child_list=""; while($fetch_all_child=$qry_all_child->fetch_assoc()) { $all_child_list.= ",".$fetch_all_child['category_id'].","; } //$all_child_list = str_replace(",,",',',$all_child_list); $array_parent_data[]=$currNode['category_id']."#".$path_height."|".$all_child_list; $array_parent_data=array_reverse($array_parent_data); for($i=0;$i<$level_change;$i++) { $tree_design.='pseudo: true, connectors: { style: { stroke: "#000000" } }, children: [ {'; } } //---------Print Node Text-------------// $tree_design .= 'text: { name: "'.trim($currNode['Name']).'" },HTMLclass: "blue",image: "images/no_member.png",'; //---------Close Leaf Brackets---------// if($path_height>0 && $lr_distance==1) { for($i=0;$i<$level_change;$i++) { $tree_design.='}]'; } } //---------Close Parent Brackets---------// foreach($array_parent_data as $key => $parent_data) { $tmp_parent=explode("#",$parent_data); $tmp_parent_id=$tmp_parent[0]; //echo $tmp_parent_id."<<>>".$currNode['parent_id']."
    "; //if($tmp_parent_id==$currNode['parent_id']) { $array_parent_data[$key] = str_replace(",".$currNode['category_id'].",",'',$parent_data); $check_child_list=explode("|",$array_parent_data[$key]); $parent_details = explode("#",$check_child_list[0]); $close_parent_id = $parent_details[0]; //if($close_parent_id==$currNode['parent_id'] && empty($check_child_list[1])) if(empty($check_child_list[1])) { //echo $tmp_parent_id."<<>>".$currNode['parent_id']."
    "; $close_parent_height = $parent_details[1]; $close_parent_height=($close_parent_height=="")?0:$close_parent_height; $level_change_parent = $close_parent_height/10; //echo $close_parent_id."|".$close_parent_height."
    "; for($i=0;$i<$level_change_parent;$i++) { $tree_design.='}],'; } unset($array_parent_data[$key]); } } } //print_r($array_parent_data); //---------------------------------------// // Check if there's chidren if ($index != $lastNodeIndex && $tree[$index + 1]['depth'] <= $tree[$index]['depth']) { $tree_design .= '},'; // If not, close the
  • } // Adjust current depth $currDepth = $currNode['depth']; // Are we finished? if ($index == $lastNodeIndex) { $tree_design .= '' . str_repeat('}],', $currDepth); } } //End Loop //-----------------------------------------------------// ?> Tree