jquery-ztree從後臺獲取數據的例子

引入:

  <link rel="stylesheet" href="../plugins/jquery-ztree/css/demo.css" />
    <link rel="stylesheet" href="../plugins/jquery-ztree/css/zTreeStyle.css" />
    <script type="text/javascript" src="../skeleton/jquery-1.11.3.js"></script>
    <script type="text/javascript" src="../plugins/jquery-ztree/js/jquery.ztree.core-3.5.js" ></script>

前臺:

<div style=" overflow:scroll; width:20%; height:620px;float:left;background: #f0f6e4;">
    <div class="zTreeDemoBackground left">
        <ul id="treeDemo" class="ztree"></ul>
    </div>
</div>

腳本:

 var setting = {};
    $(document).ready(function(){
        $.fn.zTree.init($("#treeDemo"), setting, getTree());
    });


 function getTree() {
        var tree = {};
        $.ajax({
            url: "/tree/query5",
            type: "post",
            contentType: "application/json",
            timeout: 30000, //超時時間:30秒
            async: false,//false-同步(當這個ajax執行完後纔會繼續執行其他代碼);異步-與其他代碼互不影響,一起運行。
            dataType: "json",
            success: function (data) {
                console.log(data);
                tree = data;
            }, error: function (data) {
                console.log(data);
            }
        });
        return tree;
    }

後臺:

   @RequestMapping("/query5")
    public String queryForZtree() {
        String path = System.getProperty("user.dir");
        File f = new File(path+"//fillforztree.json");
        if(f.exists()){
           return  FileUtil.fileToString(path+"//fillforztree.json",null,"utf-8");
        }else{
            List<Map<String, Object>> list = new ArrayList<>();
            String content = getTreeForZtree(null, list);
            FileUtil.writeFile(path+"//fillforztree.json", content,false);
            return content;
        }
    }

public static String getTreeForZtree(String path, List<Map<String, Object>> list) {
        String newPath = " ";
        if (path == null) {
            path = "E:\\test";
        }
        List<File>objs = FileUtil.getFiles(path);
        for (File s : objs) {
            if (String.valueOf(s).indexOf(".") == -1) {//如果是目錄
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", path+"\\"+s.getName());
                map.put("name", s.getName());
                map.put("isParent", "true");
                newPath = path.concat("\\").concat(s.getName());
                if (FileUtil.isDirectory(newPath)) {//如果是目錄,往下搜索
                    List<Map<String, Object>> childList = new ArrayList<Map<String, Object>>();
                    map.put("children", childList);
                    getTreeForZtree(newPath, childList);
                }
                list.add(map);
            } else {//如果是文件
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", path+"\\"+s.getName());
                map.put("name", s.getName());
                list.add(map);
            }
        }

        return JSONArray.toJSONString(list);
    }

工具FileUtil:

	public static List<File> getFiles(String folderPath) {
		File fileDir = new File(folderPath);
        File[] files = fileDir.listFiles();
		List<File> fileList = new ArrayList<File>();
		for (File f : files) {
			fileList.add(f);
		}
		Collections.sort(fileList, new Comparator<File>() {
			@Override
			public int compare(File o1, File o2) {
				if (o1.isDirectory() && o2.isFile())
					return -1;
				if (o1.isFile() && o2.isDirectory())
					return 1;
				return o1.getName().compareTo(o2.getName());
			}
		});
		return fileList;
	}

public static String fileToString(String file,String addRow, String charSet) {
		BufferedReader buf = null;
		String str = null;
		StringBuffer sb = new StringBuffer();
		try {
			buf = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));

			while ((str = buf.readLine()) != null) {
				sb.append(str);
				if(addRow!=null)
				sb.append(addRow);
			}
			buf.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (buf != null) {
				try {
					buf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		String result = sb.toString();
		// return result.substring(0, result.lastIndexOf("\r\n"));
		return result;
	}


public static void writeFile(String filePath, String content, boolean needRename) {
		String realPath = null;
		if (needRename) {
			realPath = rename(filePath);
		} else {
			realPath = filePath;
		}
		// FileOutputStream會出現中文亂碼,用 OutputStreamWriter
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(new FileOutputStream(realPath), "utf-8");
			osw.write(content);
			osw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				osw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

效果圖: 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章