码迷,mamicode.com
首页 > Web开发 > 详细

jsTree通过AJAX从后台获取数据

时间:2015-09-07 10:58:10      阅读:730      评论:0      收藏:0      [点我收藏+]

标签:

页面代码:

<div id="MenuTree"></div>

javascript代码:

$(document).ready(function ($) {
  InitMenuTree();
});

function InitMenuTree() {
  $(‘#MenuTree‘).data(‘jstree‘, false);
  $.getJSON(‘@Url.Action("GetMenuTree", "AdminMenu")‘, function (json) {
    $(‘#MenuTree‘).jstree({
      ‘core‘: {
        ‘data‘: json
      }
    });
  });
  $(‘#MenuTree‘).on(‘changed.jstree‘,function (node,data){
    var id = data.instance.get_node(data.selected[0]).id;//节点点击事件 获取ID
    ClickMenuTree(id);
  })
  $(‘#MenuTree‘).on(‘loaded.jstree‘, function (e, data) {
    data.instance.open_all();//默认展开所有节点
  })
}

使用jQuery的getJson方法从后台获取数据,然后直接放到data后面就行了。


后台代码:

Models:(这是jstree要求的格式)

    public class AdminMenuTreeNoteModel
    {
        public string id { get; set; }
        public string parent { get; set; }
        public string text { get; set; }
        public string icon { get; set; }
    }

Controllers:(我用的是.Net MVC 这不重要,直接把数据按照规定的JSON格式传出去就行了)

public ActionResult GetMenuTree()
{
    var trees = from a in dbc.AdminMenus
                select new AdminMenuTreeNoteModel
                {
                    id = a.ID.ToString(),
                    parent = (a.ParentMenu > 0 ? a.ParentMenu.ToString() : "#"),//默认根节点的parent是“#”
                    text = a.Title,
                    icon = (a.IconClass.Length > 0 ? a.IconClass : "icon-doc")//部分节设定好了图标,没有图标的使用默认图标
                };
    return Json(trees.ToList(), JsonRequestBehavior.AllowGet);
}

 完事,还是很简单的。但是JsTree的官方网站里的文档根本看不懂。

 


这里是规定的JSON格式:

// Alternative format of the node (id & parent are required)
{
  id          : "string" // required
  parent      : "string" // required
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
}


 

jsTree通过AJAX从后台获取数据

标签:

原文地址:http://www.cnblogs.com/ANPY/p/4788155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!