我想用新的json数据替换jstree树的全部内容.
我正在使用jsTree 1.0从github下载2011年7月25日
说我有这个功能
function init_my_tree(my_json_data)
{
$("#demo1").jstree({
themes: {
"theme": "classic","dots": false,"icons": true,"url": "//js.myliburl.com/jstree/themes/classic/style.css"
},json : {
data : my_json_data
},plugins : [ "core","ui","themes","json" ]
});
}
其中demo1指的是a
<div id="demo1"></div>
我想要做的是使用从我的服务器加载的新数据完全替换树.但是,为了这个问题,让我们假装我只想这样做
$(document).ready(function() {
var text_data = '[{"title":"All","data":{"jstree":{"opened":true}},"children":[{"title":"Item 1","data":{"jstree":{}},"children":false,"li_attr":{"id":"1","class":"jstree-leaf","href":"#"},"a_attr":{"href":"#"}},{"title":"Item B","li_attr":{"id":"2","class":"jstree-last","a_attr":{"href":"#"}}],"li_attr":{"id":"0","a_attr":{"href":"#"}}]';
var my_json_data = $.parseJSON(text_data);
init_my_tree(my_json_data); // initialize the tree view
text_data = '[{"title":"Something Else","children":[{"title":"Item A",{"title":"Item 2","a_attr":{"href":"#"}}]';
my_json_data = $.parseJSON(text_data);
init_my_tree(my_json_data); // re-initialize the tree view to load with new data
});
我正在做这个基于这个链接,Ivan似乎主张这个
http://groups.google.com/group/jstree/browse_thread/thread/b40a1f0ab0f9a66b?fwc=2
然而,发生的情况是,在第二次调用init时,我最终在firebug中收到这个错误
instance._get_settings is not a function
我试着打电话
$("#demo1").jstree("destroy");
但这并没有解决我的问题.
如何用新的json数据替换整个树?
解决方法
这是我如何解决这个问题:
– 将树的所有绑定和初始化包装在一个函数中
– 从我的document.ready函数调用此函数(这将处理树的初始设置)
– 在我的ajax调用的成功回调中,我销毁树,然后再次调用该函数
– 将树的所有绑定和初始化包装在一个函数中
– 从我的document.ready函数调用此函数(这将处理树的初始设置)
– 在我的ajax调用的成功回调中,我销毁树,然后再次调用该函数
以下是代码:
function loadTargetTree() {
$("#target-book-tree").bind("select_node.jstree",function (e,data) {
data.rslt.obj; // the LI node that was clicked
selectedTargetID = data.rslt.obj.attr("id");
if(data.rslt.obj.hasClass("book") || data.rslt.obj.hasClass("section")) {
targetChapterIsSelected = false;
togglecopyTools()
} else {
targetChapterIsSelected = true;
togglecopyTools();
target_parent_id = selectedTargetID;
}
});
$("#target-book-tree")
.jstree({
core : {
"initially_open" : ["book_"+getParameterByName('target_book_id')],"animation": 100
},"plugins":["themes","html_data","ui"],"themes" : {
"theme" : "classic","dots" : true,"icons" : false
},"ui" : {
"select_limit" : 1,"selected_parent_close" : "deselect",},});
}
$(document).ready(function() {
loadTargetTree();
});
AND MY AJAX CALL:
var sendData = 'new_name='+$('input#new_name').val()+'&target_book_id='+target_book_id + '&source_lib_id='+source_lib_id + '&target_parent_id='+target_parent_id;
$.ajax({
dataType: "json",type: "POST",url: "/ajax/copySelectedSection",data: sendData,error: function(data) {
alert("Oops! An error occured. Please try again later.")
},success: function(data) {
if (data['status'] == "ok") {
$("div#target-book-tree").html(data['book_outline']);
$("#target-book-tree").jstree('destroy');
loadTargetTree();
} else {
alert("Sorry,...");
}
}
})