2015-06-21 34 views
3

我正在使用JSTree創建我擁有的數據的樹結構。jstree html和json

我正在使用Scala模板。模板文件創建html。該html有一個SJTree div標記,並且還正確顯示第一級子樹,但我想進行ajax調用以進一步展開樹。

下面是我的代碼有

@(course:models.CourseDetails,realtedCourses:List[models.CourseDetails]) 
     @import helper._ 
     @importhelper.twitterBootstrap._ 

     @main() { 
     @wflash() 

<div id="jstree"> 
<!-- in this example the tree is populated from inline HTML --> 
<ul> 
    <li id="@{course.wnCourseName}"><font color="black">@course.wnCourseName</font> 
    <ul> 
    @for(children1 <- realtedCourses) { 
     <li id="@{children1.wnCourseName}"> <b><font color="blue">@children1.wnCourseName</font></b></li> 
     } 
    </ul> 
    </li> 
</ul> 
</div> 

<div id="CourseData" class="tree well"> 
    @views.html.display.displayCourseInfo(course)</div> 
</div> 

和JavaScript代碼是

$('#jstree').jstree(); 
$('#jstree').jstree({ 
    'core' : { 
     'data' : { 
      'url' : function (node){ 
       if (node.id === '#') 
       { 
        return "http://localhost:9000/getCourses/" ; 
       }else 
        return "http://localhost:9000/getCourses/" + node.id; 
      }, 
      'data' : function (node) { 
       return { 'id' : node.id }; 
      } 
     } 
    } 
}); 

我要調用的AJAX功能僅適用於點擊事件的子樹。我看到JSTree插件中的事件部分,但不知道如何在事件上對服務器進行ajax調用並更新樹。

服務器端的JSON響應

[ 
    { 
    "data":"Science", 
    "attr":{ 
     "id":"Science" 
    }, 
    "state":"closed" 
    }, 
    { 
    "data":"Commerce", 
    "attr":{ 
     "id":"Commerce" 
    }, 
    "state":"closed" 
    }, 
    { 
    "data":"Arts", 
    "attr":{ 
     "id":"Arts" 
    }, 
    "state":"closed" 
    } 
] 

我應該包括parent屬性呢?

理想情況下,我想對事件做一個ajax調用並更新樹。

回答

2

您不應該創建兩次樹。請記住,混合使用HTML和JSON數據源將很難實現。如果你可以創建一個JS變量,它將保存最初的樹,然後移動到AJAX,會更好。無論如何,您需要使用core.data作爲功能。

如果你堅持HTML與JSON相結合,您必須先存儲原始的HTML,然後進行AJAX,就像這樣:

var tmp = $('#jstree').html(); 
$('#jstree').jstree({ 
    "core" : { 
     "check_callback" : true, 
     "data" : function (node, cb) { 
      if(node.id === "#") { 
       cb(tmp); 
      } 
      else { 
       // enhance the AJAX call as needed (verb, data) 
       $.ajax({ url : "http://localhost:9000/getCourses/" + node.id }) 
        .done(function (data) { cb(data) }); 
      } 
     } 
    } 
}); 

這裏是一個工作演示(當然沒有的AJAX ):
http://jsfiddle.net/DGAF4/542/

+0

感謝Vakata解決方案似乎工作。我已經接受它作爲答案,還有1個問題。有沒有辦法檢測類似於所選節點的圖標上的點擊事件。 –

+0

在'changed'和'select_node'事件中,您將原始事件作爲'data.event':'$('#tree')。on('select_node.jstree',function(e,data){... })'。使用data.event.target.closest('。jstree-icon')。length可以確定點擊是在圖標還是文本上。 – vakata