jQuery onChange отправляет значение select в JsTree, используя AJAX - PullRequest
0 голосов
/ 01 марта 2019

Я пытаюсь отправить значение выбора в файл с именем «response.php? Operation = get_node & idcuatrimestre = ...» (это возвращает JSON-код JsTree и возвращает разные результаты в зависимости от второго параметра «idcuatrimestre»),Проблема в том, что при использовании AJAX вы отправляете параметр, но не знаете, как обновить JsTree, чтобы он изменил значение указанного

<form method="post">
    <select name="idcuatrimestre" onchange="fetch_select_left(this);" class="select">
        <option>Please Select</option>
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
</form>

<div id="test-result">#nc</div>

<div id="tree-container"></div> <!-- Here load the JsTree menu -->

<script>    <!-- Send to response -->
    function fetch_select_left(idcuatrimestre){
        var idc = idcuatrimestre.value; //alert(idc);   //value of Select
        $.ajax({
            url: "../ajax/jstree/response.php",
            data: { operation: "get_node", idcuatrimestre: idc }, //Equals to:  "response.php?operation=get_node&idcuatrimestre=..." + idc,
            type: "GET",
            success: function(html){
                //alert(html);
                $("#test-result").html(html);   //Here it does a test, it just returns the value of the select and writes it in a div #test-result
                //This is where in theory I should refresh JTree with the new value but I do not know how
            }
        });
    }
</script>

И именно так я инициализирую JsTree при входе на страницу

<script type="text/javascript">
    $(document).ready(function(){ 
        //fill data to tree  with AJAX call
        $('#tree-container').jstree({
            'core' : {
                'data' : {
                    'url' : '../ajax/jstree/response.php?operation=get_node',   //Final
                    'data' : function (node) {
                    return { 'id' : node.id, 'text' : node.text };
                },
                "dataType" : "json"
            }
            ,'check_callback' : true,
            'themes' : {
                'responsive' : false
            }
        },
        'plugins' : ['state','contextmenu','wholerow','search']
        })
        .on('create_node.jstree', function (e, data) {
            $.get('response.php?operation=create_node', { 'id' : data.node.parent, 'position' : data.position, 'text' : data.node.text })
                .done(function (d) {
                    data.instance.set_id(data.node, d.id);
                })
                .fail(function () {
                    data.instance.refresh();
                });
            }).on('rename_node.jstree', function (e, data) {
                $.get('response.php?operation=rename_node', { 'id' : data.node.id, 'text' : data.text })
                    .fail(function () {
                        data.instance.refresh();
                    });
                }).on('delete_node.jstree', function (e, data) {
                    $.get('../ajax/jstree/response.php?operation=delete_node', { 'id' : data.node.id })
                        .fail(function () {
                            data.instance.refresh();
                        });
                    })
                    //Solo para trabajar con un nodo a nivel "cargas": ...

                    //No todos los nodos tienen habilitado el plugin "contextmenu"
                    .on('show_contextmenu.jstree', function(e, reference, element) {
            //                  if ( reference.node.parents.length < 1 || reference.node.parents.length > 1 //Este solo deshabilita los planes
                                if (  reference.node.parents.length < 1 || reference.node.parents.length > 1 || reference.node.parents.length > 1  
                                // || reference.node.parents.length > 2 
                                ) {
                                      $('.vakata-context').remove();
                                };
                            })

                //Links
            //              .on("activate_node.jstree", function (e, data) {
                            .on("activate_node.jstree", function (e, data) {
                                if(data.node) {
                                    var href = data.node.a_attr.href;
                                    window.location.href = href;
                                }
                            })                

            });
</script>

Обе части работают, но я хочу объединить их так, чтобы jsTree возвращал JSON по-разному в соответствии с параметрами выбора.Я надеюсь, что вы хорошо объяснили мне, и, пожалуйста, вы можете мне помочь.Спасибо

1 Ответ

0 голосов
/ 02 марта 2019

Поскольку вы используете AJAX для загрузки данных, обновление jsTree вызовет URL-адрес, указанный в core.data.url конфигурации.Поэтому, когда значение вашего выбранного входа изменяется, вы должны добавить idcuatrimestre к обратному вызову jstree ajax, а затем обновить дерево.Затем метод refresh обновляет все дерево с помощью нового обратного вызова.

function fetch_select_left(sel){
    var oTree = $('#tree-container').jstree(true);
    var idc = sel.value;
    oTree.settings.core.data = {
        'url' : '../ajax/jstree/response.php?operation=get_node',   //Final
        'data' : function (node) {
            return { 'id' : node.id, 'text' : node.text, idcuatrimestre: idc };
        }
    };
    oTree.refresh();            
}
...