daweilv / treejs

A lightweight tree widget, compatible with VanillaJS / React / Vue. Tiny size after gzip. Zero dependence.
MIT License
142 stars 49 forks source link

TypeError with data via url #22

Open Wonko52 opened 2 years ago

Wonko52 commented 2 years ago

I got a JS-Error when I try to get data via Url:

Uncaught TypeError: can't convert undefined to object

This is the code:

    const myTree = new Tree('#myTree', {
      url: 'http://localhost:8000/treeviewJson',
      method: 'GET',
    });

But this works:

let url = 'http://localhost:8000/treeviewJson';

fetch(url)
.then(res => res.json())
.then(out => {

  const myTree = new Tree('#myTree', {
    data: [out],
    })
}
  );

This is the response of the URL

# curl http://localhost:8000/treeviewJson
{"id":"0","text":"Node 0","children":[{"id":1,"text":"Node 0-1"},{"id":2,"text":"Node 0-2"}]}[]

It's generate by PHP:

function treeviewJson(): Response
    {
        $data = [
            'id' => '0',
            'text' => 'Node 0',
            'children' => [
                [
                    'id' => 1,
                    'text' => 'Node 0-1'
                ],
                [
                    'id' => 2,
                    'text' => 'Node 0-2'
                ],
            ]
        ];

        $response = new Response();
        $response->setContent(json_encode($data));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
}
DarthSonic commented 1 year ago

I get the same exception: #25

THenkeDE commented 1 year ago

maybe just my 2cent but your return should be an array itself like

        $data = [
[
            'id' => '0',
            'text' => 'Node 0',
            'children' => [
                [
                    'id' => 1,
                    'text' => 'Node 0-1'
                ],
                [
                    'id' => 2,
                    'text' => 'Node 0-2'
                ],
            ]
]
        ];

that will result in this json

[
  {
    "id": "0",
    "text": "Node 0",
    "children": [
      {
        "id": 1,
        "text": "Node 0-1"
      },
      {
        "id": 2,
        "text": "Node 0-2"
      }
    ]
  }
]