golang組建目錄嵌套json使用jstree顯示

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
  • 目的:在瀏覽器上瀏覽電腦指定目錄。
  • 技術: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.