前端:
<div id="chart-container"></div>
JavaScript:
//ajax获取根节点的所有子节点,通过子节点查询数据库内的它的子节点,以此类推
//树形图初始化,传入数据chart_data
//数据格式:{'name':xxx,'title':xxx,'children':[{'name':xxx,'title':xxx,'children':[...]},{'name':xxx,'title':xxx,'children':[...]},...]}
let oc = $('#chart-container').orgchart({
'data' : chart_data,
'chartClass': 'edit-state',
'exportButton': false,
'exportFilename': 'SportsChart',
'createNode': function($node, data) {
$node[0].id=data.title;
}
});
//获取数据库查询到的data
$.ajax({
async:false,
method:'post',
type:'json',
data:{
"id":xxx_id,
},
url:'/xxx/initCharts/',
success:function(result){
let res=result.data;
if (res[1].length==0) {
children=null;
}else {
charts_tree(res);
}
chart_data = {'name': res[0][0].xxx_name,'title':res[0][0].xxx_id,"children":children}
},
error:function(e){
console.log(e);
chart_data=""
}
});
//指标体系树图的递归实现
function charts_tree(res){
let children_list=[];
for (let i=0;i<res[1].length;i++) {
$.ajax({
async: false,
method: 'post',
type: 'json',
data: {
"id": res[1][i].xxx_id,
},
url: '/xxx/initCharts/',
success: function (result) {
let res=result.data
if(res[1].length==0){
children=null;
}else {
charts_tree(res);
}
},
});
let children_data= {'name':res[1][i].xxx_name,'title':res[1][i].xxx_id,"children":children};
children_list.push(children_data);
}
children=children_list;
}
后台(python):
# 初始化指标体系树形图
def initCharts(request):
res = {'code': 400, 'flag': False, 'data': ""}
data_list=[]
sql = "select * from xxx表 where xxx_id = '%s'"
sql2 = "select * from xxx表 where pid = '%s'"
xxx_id = request.POST.get("xxx_id")
data1 = db.query_sql(sql % xxx_id)
data2 = db.query_sql(sql2 % xxx_id)
data_list.append(data1)
data_list.append(data2)
try:
res['code'] = 200
res['flag'] = True
res['data'] = data_list
except Exception as e:
res['data'] = "修改失败!ERROR: "+str(e)
return JsonResponse(res)
表结构字段:
id pid xxx_id
id唯一
id在添加时同时添加相同的xxx_id
pid的值如果等于某条数据id值,那么就是它的子节点