简体   繁体   中英

How to use json data in html

I have json with js file list.js and I am trying to get the data from it in HTML file index.html .Tell me please how to connect it with HTML.

Here's my json with js file:

 $(function () {

      var categories = {
        menu: [{
          title: "animals",
          children: [{
            title: "insects",
            children: [{
              title: "ant",
              title: "bee",
              title: "fly"
            }]
          },
          {
            title: "mammals",
            children: [{
              title: "bear",
              title: "platypus",
              title: "tiger"
            }]

          },
          {
            title: "reptiles",
            children: [{
              title: "crocodile",
              title: "turtle"
            }]
          }
          ]
        },
        {

          title: "fruits",
          children: [{
            title: "apple",
            title: "pineapple",
            title: "pear"
          }]

        },
        {
          title: "vegetables",
          children: [{
            title: "potato",
            title: "tomato",
            title: "carrot"
          }]
        }]
      };
      var getMenuItem = function (itemData) {
        var item = $("<li>")
          .append(
          $("<a>", {
            html: itemData.title
          }));
        if (itemData.children) {
          var childrenList = $("<ul>");
          $.each(itemData.children, function () {
            childrenList.append(getMenuItem(this));
          });
          item.append(childrenList);
        }
        return item;
      };

      var $menu = $("#menu");
      $.each(categories.menu, function () {
        $menu.append(
          getMenuItem(this)
        );
      });
      $menu.menu();
});

The idea is to make unfolding menu to show these types Animals-Insects-ant,fly,bee;Mammals-bear,platypus,tiger;Reptiles-crocodile,turtle;.Please help, I am new to this field.:(

This post explains very well you you can combine an external JSON file with an html file: How to read an external local JSON file in Javascript

However! What you are having is not an json file. What i would suggest is getting your JSON data, store it within its own file and use the .json extension and then follow the example shown in the post

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