layui tree组件如何异步加载数据,动态添加树节点

<?php
    
    $data = [
        [ 'id' => 1, 'name' => '江苏省', 'pid' => 0],
        [ 'id' => 2, 'name' => '徐州市', 'pid' => 1],
        [ 'id' => 3, 'name' => '睢宁县', 'pid' => 2],
        [ 'id' => 4, 'name' => '双沟镇', 'pid' => 3],
        [ 'id' => 5, 'name' => '王集镇', 'pid' => 3],
        [ 'id' => 6, 'name' => '铜山区', 'pid' => 2],
        [ 'id' => 7, 'name' => '张集镇', 'pid' => 6],
        [ 'id' => 8, 'name' => '大黄山镇', 'pid' => 6],
        [ 'id' => 9, 'name' => '南京市', 'pid' => 1],
        [ 'id' => 10, 'name' => '江宁区', 'pid' => 9],
        [ 'id' => 11, 'name' => '鼓楼区', 'pid' => 9],
        [ 'id' => 12, 'name' => '浙江省', 'pid' => 0],
        [ 'id' => 13, 'name' => '杭州市', 'pid' => 12],
        [ 'id' => 14, 'name' => '西湖区', 'pid' => 13]    
    ];

    $res = [];
    $tree = [];
    //整理数组
    foreach ($data as $key => $value) {
        $res[$value['id']] = $value;
        $res[$value['id']]['children'] = [];
    }
    
    unset ($data);
    //查询子孙
    foreach ($res as $key => $value) {
        if($value['pid'] != 0){
            $res[$value['pid']]['children'][] = &$res[$key];
        }
    }
    //去除杂质
    foreach ($res as $key => $value) {
        if ($value['pid'] == 0){
            $tree[] = $value;
        }
    }
    unset($res);
    
    $tree = json_encode($tree);?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>树模块 - layui</title>
<link rel="stylesheet" href="layui-master/build/css/layui.css">
<style>
body{padding: 50px 100px;}
</style>
</head>
<body>
<?php require 'mytree.php'; ?>

<ul id="demo"></ul>

<script src="layui-master/build/lay/dest/layui.all.js"></script>
<script>

layui.use('tree', function(){
  var tree = layui.tree({
    elem: '#demo' //指定元素
    //,check: 'checkbox' //勾选风格
    ,skin: 'as' //设定皮肤
    ,target: '_blank' //是否新选项卡打开(比如节点返回href才有效)
    ,drag: true
    ,click: function(item){ //点击节点回调
      console.log(item)
    }
    ,nodes: <?php echo $tree; ?>
  });

});
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/huhewei/p/13138354.html