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.新建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
7.在index.html.erb文件中添加
<div id="treeDemo" class="ztree"></div>

<%= javascript_include_tag "tree" %>
8.新建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);
9.效果

rails中的zTree异步加载

10.需要更多功能,请参考ztree官方文档

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

11.源码下载地址

Ztree点此下载

你可能感兴趣的:(Rails)