rails中的zTree異步加載

rails+coffeescript+zTree

1.新建rails項目Ztree(rails new Ztree)

2.gemfile中添加ztree的引用

#jquery樹插件
gem 'jquery-ztree-rails'
3.application.js和application.css中添加
//= require ztree.all

 *= require ztree
4.使用scaffold生成person的crud(ctrl+alt+g -> scaffold)
Person name:string parent:references sex:integer age:integer phone:string address:string isleaf:boolean
5.在people_controller添加people_tree方法和修改person_params方法
  def people_tree
    @people = nil
    if params[:id] == nil
      @people = Person.select("id,name,parent_id").where("parent_id is null")
    else
      @people = Person.select("id,name,parent_id").where("parent_id = ?", params[:id])
    end

    if @people.length > 0
      @people.each do |person|
        person.isleaf = false
        if Person.where("parent_id = ?", person.id).count > 0
          person.isleaf = true
        end
      end
    end
    render 'tree'
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def person_params
    params.require(:person).permit(:name, :parent_id, :age, :sex, :phone, :address, :isleaf)
  end

6.添加路由

  get 'people/people_tree' => 'people#people_tree'

  resources :people

7.新建tree.json.jbuilder文件,將對象解析成json數據供ztree使用

json.array!(@people) do |person|
  json.id person.id
  json.parent_id person.parent_id
  json.name person.name
  json.isParent person.isleaf
end
8.在index.html.erb文件中添加
<div id="treeDemo" class="ztree"></div>

<%= javascript_include_tag "tree" %>
9.新建coffeescript文件tree.coffee
$ = jQuery

zTreeNodes = null;
zTreeObj = null;

#瀏覽器報錯cannot resolve symbol 'msie' 解決方法
jQuery.browser = {}
$ ->
  jQuery.browser.msie = false
  jQuery.browser.version = 0
  if(navigator.userAgent.match(/MSIE ([0-9]+)\./))
    jQuery.browser.msie = true
    jQuery.browser.version = RegExp.$1

#ztree設置
setting = {
  async: {
    enable:true,     #異步加載可用
    dataType: "json",     #接收json數據
    type: "get",          #使用get請求
    url: "/people/people_tree.json",   #請求url
    autoParam: ["id"]            #異步加載是請求的參數
  },
  check: {
    enable: true           #checkbox可用
  },
  data: {
    simpleData: {
      enable: true,
      idKey: "id",
      pIdKey: "parent_id",
      rootKey: "0"
    }
  },
  view: {
    dbClickExpand: false,       #雙擊展開不可用
    showLine: false             #不顯示下劃線
  },
  edit: {
    enable: true,               #可編輯
    showRemoveBtn: true,        #顯示刪除圖標
    showRenameBtn: true,        #顯示編輯圖標
    removeTitle: "刪除節點",
    renameTitle: "編輯名稱"
  },
  callback: {
    onAsyncSuccess: zTreeOnAsyncSuccess          #請求成功後的回調函數
  }
}

zTreeOnAsyncSuccess = (event, treeId, treeNode, data) ->
  zTreeNodes = data

zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
10.效果

11.需要更多功能,請參考ztree官方文檔

http://www.ztree.me/v3/main.php

12.源碼下載地址

                                       Ztree點此下載

發佈了37 篇原創文章 · 獲贊 7 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章