Replacing jstree node with ajax call

I have a jstree object that I use to store data, and I use ajax to complete it after the step. I call the ajax.php file, which will return the nodes formatted in HTML, depending on the data that I send to it.

My problem is this: I know that the data that I receive already contains the structure of the current node, and instead of replacing the current node with the data that it receives from the ajax call, jstree adds the structure to the current nodes as a new son, which I don’t want.

For example, if I click on node 1:

0 | - 1 | - 2 

I will get the following structure:

 0 | - 1 | | - 1 | | | - 1.1 | | | - 1.2 | - 2 

I cannot change the return of the ajax call, however, I thought that it would be possible to reduce the bit to the following code in order to replace the node with the returned data instead of inserting it as a child node of the current node:

 $node.jstree({ "plugins" : [ "themes", "html_data" ], "html_data" : { ajax: { url: "ajax.php", data: function(node){ return { index: (node != -1) ? node.attr("id") : 0 }; }, type: "POST" } }, animated: 'fast' }); 

Thanks so much for your answers :)

+4
source share
1 answer

Well, that’s why, having fought the jstree plugin and advised me to change my perspective with my friend, I finally decided to create my own tree bending / expanding algorithm from scratch, which is not at all difficult with jQuery and CSS, even for JavaScript beginners like me! It took me a day, but I learned a lesson well ...

JQuery

 $('.closed').on('click', changeContent); function changeContent(e) { $('.open').unbind(); $('.closed2').unbind(); $('.closed').unbind(); var $this = $(this); $this.attr('class', 'open'); $.ajax({ type: 'post', url: 'ajax.php', data: { index: $this.attr("id") }, success: function(xhr,msg) { $this.replaceWith(xhr); $('.closed').on('click', changeContent); UpdateOpen(); } }); } function UpdateOpen(e) { $('.open').unbind(); $('.closed2').unbind(); $('.open, .closed2').on('click', function(e) { e.stopPropagation(); $('.open').unbind(); $('.closed2').unbind(); var $this = $(e.currentTarget); if($this.attr('class') == 'closed2') { $this.attr('class', 'open'); $this.children('ul').show(); UpdateOpen(e); } else if($this.attr('class') == 'open') { $this.attr('class', 'closed2'); $this.children('ul').hide(); UpdateOpen(e); } }); } 

CSS

 .closed {padding-left: 7px; list-style-type: none; background: URL("/img/plus.gif") left top no-repeat; } .closed2 {padding-left: 7px; list-style-type: none; border-left: 1px dotted; background: URL("/img/plus.gif") left top no-repeat; } .open {padding-left: 7px; list-style-type: none; border-left: 1px dotted; background: URL("/img/minus.gif") left top no-repeat; } 

I know this is not the best implementation, but what I came up with is what I know about JavaScript. Please note that this code depends on how ajax.php returns data.

+2
source

Source: https://habr.com/ru/post/1481808/


All Articles