如何获取JSON数据以显示在HTML div中?

时间:2018-12-19 16:32:46

标签: javascript html json

我在uni中有这个javascript / ajax / json / HTML分配,并且它是一个披萨网站,您可以在其中构建自己的披萨。地壳,馅料和其他信息位于json文件中,我们必须将其显示在首页上,以便您可以选择自己的披萨。因此,我试图从JSON文件中获取数据,以显示在index.html上的3个不同的div中。

这是我的HTML文件:

<!DOCTYPE HTML>
<html>

<head>
    <title>Högskolan I Borås Pizza</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="css/style.css" rel="stylesheet" type="text/css" media="all" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script src="script.js"></script>
</head>

<body>
    <div class="wrap">
        <div class="wrapper">
            <div class="header">
                <div class="header_top">
                    <div class="logo">
                        <a href="#"><img src="images/logo.png" alt="" /></a>
                    </div>
                    <div class="header_top_list">
                        <ul>
                            <li>
                                <a href="contact.html"><img src="images/top_bullet1.png" alt="" /></a>
                            </li>
                            <li>
                                <a href="index.html"><img src="images/top_bullet2.png" alt="" /></a>
                            </li>
                        </ul>
                    </div>
                    <div class="clear"></div>
                </div>
                <div class="header_bottom">
                    <div class="header_img">
                        <img src="images/header_img.jpg" alt="" />
                    </div>
                    <div class="menu">
                        <ul>
                            <li>
                                <a href="index.html"><img src="images/list_img.png" alt="" />Hem</a>
                            </li>
                            <li>
                                <a href="pizza.html"><img src="images/list_img.png" alt="" />Pizza</a>
                            </li>
                            <li>
                                <a href="contact.html"><img src="images/list_img.png" alt="" />Kontakt</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="main">
                <div class="main_top">
                    <h2>Välkommen till vår pizzafabrik på Högskolan</h2>
                    <div class="main_top_strip">
                        <img src="images/main_top_strip.png" alt="" />
                    </div>
                    <div class="clear"></div>
                </div>
                <div class="content_top">
                    <div class="content_top_img">
                        <img src="images/content_top.jpg" alt="" />
                    </div>
                    <div class="content_top_data">
                        <h3>Dagens specialare</h3>
                        <p>Här nedan kan du bygga din egen pizza! Välj botten, topping och extra (dricka, sallad osv).</p>


                    </div>
                    <div class="clear"></div>
                </div>
                <div class="boxes">
                    <div class="box1">
                        <div class="box_top">
                            <h2>Välj botten</h2>
                            <div class="box_top_img">
                                <img src="images/box_top_strip.png" alt="" />
                            </div>
                            <div class="clear"></div>
                        </div>
                        <div class="box1_data">


                        </div>

                        <div class="clear"></div>
                    </div>
                    <div class="box2">
                        <div class="box_top">
                            <h2>Välj topping</h2>
                            <div class="box_top_img">
                                <img src="images/box_top_strip.png" alt="" />
                            </div>
                            <div class="clear"></div>
                        </div>
                        <div class="box2_data">


                        </div>
                    </div>
                    <div class="box3">
                        <div class="box_top">
                            <h2>Välj tillebehör</h2>
                            <div class="box_top_img">
                                <img src="images/box_top_strip.png" alt="" />
                            </div>
                            <div class="clear"></div>
                        </div>
                        <div class="box3_data">


                        </div>

                        <div class="clear"></div>
                    </div>
                    <div class="clear"></div>
                </div>
            </div>

        </div>
    </div>

</body>

</html>

这是我的JSON文件:

[
    {
        "botten": ["Krispig", "tunn"]
    },

    {
        "topping": ["kött", "kyckling", "tomat"]

    },
    {
        "extra": ["Fanta", "Coca cola", "Sprite"]

    }
]

这是我的JavaScript文件:

$.getJSON('choosepizza.json', function (choosePizzaData){

    choosePizza(choosePizzaData);
});

function choosePizza(choosePizzaData){
    var botten = "";
    var topping = "";
    var extra = "";

    $(choosePizzaData).each(function (index, value){

        $(choosePizzaData[index].botten).each(function (ii,vv){
            botten = choosePizzaData[index].botten[ii];
            $('.box1_data').append((ii + 1) + "." + botten + `<input type="checkbox" name="${botten}"/>` + "<br>"); 
        });

        $(choosePizzaData[index].topping).each(function (ii,vv){
            topping = choosePizzaData[index].topping[ii];
            $('.box2_data').append((ii + 1) + "." + topping + `<input type="checkbox" name="${topping}"/>` + "<br>"); 
        });

        $(choosePizzaData[index].extra).each(function (ii,vv){
            extra = choosePizzaData[index].extra[ii];
            $('.box3').append((ii + 1) + "." + extra + `<input type="checkbox" name="${extra}"/>` + "<br>"); 
        });

    });
}); 

这对我不起作用,我也不知道为什么。 json文件中的“ botten”信息应该显示为HTML页面中div box1中的列表,box2中的顶部等。我这次包含了整个html,并且我对我的剧本

2 个答案:

答案 0 :(得分:1)

我猜这是您要找的东西吗?

编辑

如果我遗漏了任何东西,我深表歉意,我什至不知道这是什么语言...所以我只是对一些事情进行了有根据的猜测...

// Wrap it all up in a name space so we can simulate having private properties. 
const PizzaApp = function(myNameSpace) {


  // Some in house stuff...
  const options = document.querySelector("#options");
  const root = document.querySelector("#app");
  const url = 'choosepizza.json';
  const state = {
    botten: null,
    topping: null,
    extra: null
  };


  // The method that gets the data from the server. 
  // For this example it's hard coded, but you get the idea?
  //
  // Mabe something like :- 
  // fetch(url).then(res => callback(res.json());
  const getData = callback => callback([{
      "botten": ["Krispig", "tunn"]
    },
    {
      "topping": ["kött", "kyckling", "tomat"]
    },
    {
      "extra": ["Fanta", "Coca cola", "Sprite"]
    }
  ]);


  // A function to render the user's option(s).
  const render = () => {
    root.innerHTML = `<p>Botten: ${state.botten == null ? 'N/A' : state.botten}</p>` +
      `<p>Topping: ${state.topping == null ? 'N/A' : state.topping}</p>` +
      `<p>Extra: ${state.extra == null ? 'N/A' : state.extra}</p>`;
  };


  // A function that fires when a state change has occured. 
  const onStateChange = () => render();


  // A function to handle the click events.
  // Made the assumption that you can only have one, but you could 
  // always update this so that you can append to have multiple. 
  const clickHandler = (e) => {
    const p = e.target;
    const value = p.textContent;
    const property = p.className;
    state[property] = value;
    onStateChange();
  };


  // A function to add the event listeners to the options.
  const dispatchEvents = () => options.querySelectorAll("p").forEach(p => p.onclick = clickHandler);


  // A function to simply render the options.
  const optionsRender = data => {
    const template = o => {
      let el = options;

      switch (o.type) {
        case 'botten':
          el = options.querySelector('.box1');
          break;
        case 'topping':
          el = options.querySelector('.box2');
          break;
        case 'extra':
          el = options.querySelector('.box3');
          break;
      }

      el.innerHTML += `<p class="${o.type}">${o.value}</p>`;
    };

    data.forEach(i => Object.keys(i).map(k => i[k].map(v => template({
      value: v,
      type: k
    }))));

    dispatchEvents();
  };


  // A public, or even global function that is exposed through the name space as 
  // a way to start the app. 
  myNameSpace.launch = () => {
    getData(optionsRender);
    render(); // Initial render.
  };


  // Be sure the return the object. 
  return myNameSpace;
}({});


// Finally start the app. 
PizzaApp.launch();
body {
  max-width: 960px;
  background: #eee;
  font-family: Arial, Helvetica, sans-serif;
  line-height: 1.6;
}

#options,
#app {
  max-width: calc(50% - 20px);
  box-shadow: 0.5px 0.5px 2.5px #888;
  width: 50%;
  margin: 10px;
  float: left;
  display: block;
  overflow: auto;
  box-sizing: border-box;
  padding: 15px;
  background: white;
  border-radius: 2.5px;
}

#options p:hover {
  cursor: pointer;
}

#options .botten {
  color: red;
}

#options .topping {
  color: blue;
}

#options .extra {
  color: green;
}
<div id="options">
  <div class="box box1"></div>
  <div class="box box2"></div>
  <div class="box box3"></div>
</div>
<div id="app"></div>

答案 1 :(得分:1)

您的代码有很多问题。您应该请教您的教授或更有经验的朋友来帮助您解释您做错了什么。

这是您要执行的操作的概念。我故意做一些不同的事情,以免为您做作业。

const data = [
  {
    botten: ["Krispig", "tunn"]
  },
  {
    topping: ["kött", "kyckling", "tomat"]
  },
  {
    extra: ["Fanta", "Coca cola", "Sprite"]
  }
]

data.forEach(function(dataObj){
  const category = Object.keys(dataObj)[0]
  const myList = $(`.${category}`)
  
  dataObj[category].forEach(function(element){
    myList.append(`<li><input type="checkbox" name="${element}">${element}</input></li>`)
  })
})
<div>
  <h2>Välj botten</h2>
  <ol class="botten"></ol>
</div>
<div>
  <h2>Välj topping</h2>
  <ol class="topping"></ol>
</div>
<div>
  <h2>Välj tillebehör</h2>
  <ol class="extra"></ol>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>