简体   繁体   中英

Pass a JSON array from PHP to Dynatree

I'm using Dynatree for the first time and wrote a PHP script that returns a properly formatted JSON array.

I've read the Dynatree documentation , but can't figure out how to pass in the JSON array from my PHP script so its contents can be loaded as the tree structure.

At the top of my HTML file, I'm using <?php include('tree.php') ?> which automatically returns the formatted JSON array (named $categories ). I'd also be fine with calling a function from JavaScript to retrieve the tree if that makes it easier.

Can someone show me how to deliver my array to Dynatree?

You can use a data- attribute, like this:

<?php
$dynaConfig = array('children'=>array(
    array('title' => 'Alice'), 
    array('title' => 'Bob')
));
$dynaConfigJSON = json_encode($dynaConfig);

// HTML head goes here
echo '<div id="tree" data-dyna="' . htmlspecialchars($dynaConfigJSON) . '">';
?>

<script>
$(function() {
   var dtConfig = $.parseJSON($('#tree').attr('data-dyna'));
   $('#tree').dynatree(dtConfig);
});

Here's a live example , and the corresponding full source code .

You can also separate the code of php in a file like tree.php and then call it in javascript.

<div id="tree">  </div>
<script type="text/javascript">
  $(function(){
    $("#tree").dynatree({
      initAjax: {
        url: "tree.php"
        }
      }
    }
</script>

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