简体   繁体   中英

Generating alternate JSON for jstree using php

I am trying to generate generate Alternate JSON code for jstree in my PHP controller.

I am creating what looks like the correct data, however, jstree does not display it.

My javascript looks like this:

$this->registerJs("
    $(function() {

        $('#statustree').jstree({ 
            'core' : 
            {
                'data' : 
                {
                    'datatype' : 'json',
                    'url' : '/myaccount/buildstatustree',
                }
            }
        });

        $('#statustree').on('loaded.jstree', function() 
        {
            $('#statustree').jstree('open_all');
        });
    })
", \yii\web\VIEW::POS_READY);

and my php looks like this:

    // convert to JSON format for jstree

    $tree = array();

    $parent = new stdClass();
    $parent->id = 'P1';
    $parent->parent = '#';
    $parent->text = $username;
    $tree[] = $parent;

    $student1 = new stdClass();
    $student1->id = 'S1';
    $student1->parent = 'P1';
    $student1->text = 'Poly';
    $tree[] = $student1;

    $student1 = new stdClass();
    $student1->id = 'S2';
    $student1->parent = 'P1';
    $student1->text = 'Bob';
    $tree[] = $student1;

    // convert to json and send
    header('Content-type: application/json');
    return json_encode( $tree );

My controller is getting called and is returning a string that looks like this:

[
    {"id":"P1","parent":"#","text":"user2"},
    {"id":"S1","parent":"P1","text":"Poly"},
    {"id":"S2","parent":"P1","text":"Bob"}
]

The spinner spins while the call is made, but the spinner disappears, and my tree is not displayed...

I suspect that I am not forming my Alternate JSON response correctly, but nothing I try works....

Thanks -John

The data you are generating looks fine (provided that is what you see in your dev tools as the response to the AJAX call that jsTree makes).

You might want to check if all the headers are OK - is it really served as JSON? You can also try adding the charset just in case:

header('Content-Type: application/json; charset=UTF-8');

I see you are already trying to force jQuery to treat the response as JSON regardless of headers, but use "dataType" instead of "datatype" .

If this does not work - please share what you see in the net panel of your developer console - the headers and the response to the AJAX call jsTree makes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM