golang生成目录嵌套json使用jstree显示

  • 目的:在浏览器上浏览电脑指定目录。
  • 技术:golang,jstree

1. golang生成jstree识别的json

1.1 使用”io/ioutil”读取指定目录

fileinfos, err := ioutil.ReadDir(dirpath)
if err != nil {
    log.Println("ReadDir error!" + dirpath)
}

1.2 使用”encoding/json”生成json数据

type treestate struct {
    Opened   bool `json:"opened"`
    Disabled bool `json:"disabled"`
    Selected bool `json:"selected"`
}

type filetree struct {
    Id       string            `json:"id"`
    Text     string            `json:"text"`
    Icon     string            `json:"icon,omitempty"`
    State    *treestate        `json:"state,omitempty"`
    Children bool              `json:"children,omitempty"`
    Li_attr  map[string]string `json:"li_attr,omitempty"`
    A_attr   map[string]string `json:"a_attr,omitempty"`
}

1.2.1 忽略为空的项

在声明struct时对不必要的项添加omitempty,这样在生成json时如果该项为空就会忽略。

1.2.2 嵌套json

  • struct中嵌套struct,如*treestate
state := &treestate{Selected: true} // Selected为true的话,在jstree中会默认选中
tree.State = state
  • struct中使用map,如map[string]string
// A_attr的href项表示该文件选项的链接地址
tree.A_attr = map[string]string{"href": "/download?file=" + tree.Id}

2. jstree使用ajax

<div id="using_ajax"></div>
<script type="text/javascript">
$('#using_ajax').jstree({
  'core' : {
    'data' : {
      'url' : "/tree_file",
      "dataType" : "json",
      'data' : function (node) {
        if (node.id==='#') {
          return { 'id' : "D:" }; //根目录为D盘
        } else {
          return { 'id' : node.id };
        }
      }
    }
  }
});
</script>

完整代码:

tree.html
treefile.go

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值