This is a creation in Article, where the information may have evolved or changed.
- Purpose: Browse the computer's designated directory on the browser.
- Technology: Golang,jstree
1. Golang generate JSON for jstree recognition
1.1 using "Io/ioutil" to read the specified directory
fileinfos, err := ioutil.ReadDir(dirpath)ifnil { log.Println("ReadDir error!" + dirpath)}
1.2 using "Encoding/json" to generate JSON data
typeTreestatestruct{OpenedBOOL ' JSON: ' opened 'DisabledBOOL ' JSON: ' Disabled 'SelectedBOOL ' JSON: ' Selected '}typeFiletreestruct{Idstring ' JSON: ' ID 'Textstring ' JSON: ' Text 'Iconstring ' JSON: ' Icon,omitempty 'State *treestate' JSON: ' State,omitempty 'ChildrenBOOL ' JSON: ' Children,omitempty 'Li_attrMap[string]string ' JSON: ' Li_attr,omitempty 'A_attrMap[string]string ' JSON: ' A_attr,omitempty '}
1.2.1 ignores items that are empty
Add Omitempty to unnecessary items when you declare a struct so that when the JSON is generated, it is ignored if the item is empty.
1.2.2 Nested JSON
- A struct is nested within a struct, such as *treestate
true// Selected为true的话,在jstree中会默认选中tree.State = state
- Use a map in a struct, such as map[string]string
// A_attr的href项表示该文件选项的链接地址map[string]string{"href""/download?file=" + tree.Id}
2. Jstree using Ajax
<div id="Using_ajax"></div><script type =< Span class= "Hljs-value" > "Text/javascript" ; $ ( ' #using_ajax ' ). Jstree ({: {: { ' URL ' : "/tree_file" , "DataType" : "JSON" , ' data ' : function { if (node.id===< Span class= "hljs-string" > ' # ' ) {return { ' ID ' /span>: "D:" }; //root directory is D disk } else {return { ' id ' : node.id}; } } } }});</script>
Full code:
Tree.html
Treefile.go