我使用asp.net和ajax生成Json数据。
当我尝试使用下面的代码绘制树时,另一方面它不起作用 当我把它作为静态
时,代码2部分正在工作注意:使用库treant.js
link: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 <li>
}
//---------------------------------------//
// 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 <li>
}
//---------------------------------------//
// 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);
//-------------------------------------------------------//
}
}
});
});
Code-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> details_data = new List<Details>();
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; }
}
}
}
Code-4:asp.Net Part
<%@ Page Title="" Language="C#" MasterPageFile="~/CDB/System/Common/Layout/Master/Panel.Master" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="PPL.Data.HRD.Organogram.Tree1._default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<style type="text/css">
#basic-example
{
overflow: unset !important;
}
</style>
<link href="../../../../../CDB/System/Assets/plugins/Organogram/Treant.css" rel="stylesheet" />
<link href="../../../../../CDB/System/Assets/plugins/Organogram/basic-example.css" rel="stylesheet" />
<script src="../../../../../CDB/System/Assets/plugins/Organogram/raphael.js"></script>
<script src="../../../../../CDB/System/Assets/plugins/Organogram/Treant.js"></script>
<script src="default.js"></script>
<div class="content-wrapper" style="padding:0;margin:0;">
<!-- Main content -->
<section class="content">
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Book Progress</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-sm-12">
<div class="form-group" style="overflow:scroll;">
<div class="chart" id="basic-example"></div>
</div>
</div>
</div>
<div class="box-footer">
</div>
</div>
</div>
<!-- /.box -->
</div>
</div>
</section>
</div>
</asp:Content>
答案 0 :(得分:2)
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
}
答案 1 :(得分:1)
我现在在PHP代码中有解决方案,我想通过使用Ajax和jQuery将其转换为asp.net
<?php
include('../../connection/connection.php');
error_reporting(0);
//--------------Tree Design---------------//
$sql_tree = "SELECT node.category_id,node.`name` AS Name, (COUNT( parent.`category_id` ) -1) AS depth,node.`lft`,node.`rgt`,
IFNULL((SELECT `category_id`
FROM `nested_category` t2
WHERE t2.lft < node.lft AND t2.rgt > 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']."<br>";
//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']."<br>";
$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."<br>";
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 <li>
}
// Adjust current depth
$currDepth = $currNode['depth'];
// Are we finished?
if ($index == $lastNodeIndex) {
$tree_design .= '' . str_repeat('}],', $currDepth);
}
} //End Loop
//-----------------------------------------------------//
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title> Tree </title>
<link rel="stylesheet" href="Treant.css">
<link rel="stylesheet" href="basic-example.css">
<style type="text/css">
#basic-example
{
overflow: unset !important;
}
</style>
</head>
<body>
<div class="chart" id="basic-example"></div>
<script src="jquery-1.10.2.js"></script>
<script src="raphael.js"></script>
<script src="Treant.js?id=<?php echo rand(); ?>"></script>
<!--<script src="basic-example.js"></script>-->
<script>
var chart_config = {
chart: {
container: "#basic-example",
nodeAlign: "BOTTOM",
connectors: {
type: "step"
},
node: {
HTMLclass: "nodeExample1"
}
},
nodeStructure: {
//---------------------------------------------//
<?php echo $tree_design; ?>
//text: { name: "BOD" },HTMLclass: "blue",image: "images/no_member.png",children: [{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Kawser Hasan (Chairman)" },HTMLclass: "blue",image: "images/no_member.png",},{ connectors: { style: { stroke: "#000000" } },text: { name: "Engr. Md. Abdullah Al Baki (Managing Director)" },HTMLclass: "blue",image: "images/no_member.png",}],
//---------------------------------------------//
}
};
new Treant( chart_config );
</script>
</body>
</html>