将菜单从php json文件输出到html时遇到麻烦

问题描述 投票:0回答:1

我获得了一个任务,该任务基本上需要一个json文件,然后通过javascript将内容输出到菜单。我已经绘制了一些代码,但是没有用。该任务需要通过api将JSON文件输出到html,以便客户可以订购。另外,它还必须将订单作为JSON字符串保存到localstorage(browser)。最后,它基本上需要使用按钮(onClick)发出命令。所以现在我的问题是当我将“订单”的ID添加到容器div元素时,我的页面变成白色。我不知道为什么会这样,但是我想尽可能保留这种格式(设计)。其次,自从输出白色使我的页面大声笑之后,这没有别的了。但是我需要首先克服这个第一个障碍。我将分享我的代码(html,js和css)。任何帮助或指示,将不胜感激!

//get menu from api
var getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('get', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status == 200) {
      callback(null, xhr.response);
    } else {
      callback(status);
    }
  };
  xhr.send();
};

/*
{
"menu": {
"slice of pizza": "2.00",
qty_slice of pizza
"toppings": {
  "pepperoni": ".25",
  "meatballs": ".35",
  "mushrooms": ".40",
  "olives": ".20"
},
"sides": {
  "potato salad": "1.25",
  "hummus": "2.50",
  "caesar salad": "3.50",
  "garden salad": "2.25"
},
"drinks": {
  "soda": {
    "small": "1.95",
    "medium": "2.20",
    "large": "2.50"
  },
  "juice": "2.00",
  "water": "1.25"
   }
   }
  }
 */

getJSON('https://mm214.com/menu.php', function(err, data) {
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {

    var content = '';

    for (x in data.menu) {
      if (typeof(data.menu[x]) == 'object') {
        for (y in data.menu[x]) {
          if (typeof(data.menu[x][y]) == 'object') {
            for (z in data.menu[x][y]) {
              content += z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '"><br>';
            }
          } else {
            content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '"><br>';
          }
        } //closes y in data

      } else {
        content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '"><br>';

      } //else for data.menu[x] if not an object
    }
  } //closes outer for loop

  //localStorage only stores strings! Stringify turns objects into strings!
  //parse converts JSON strings to objects that can be looped around

  document.getElementById("menuOutput").innerHTML = content;
  localStorage.setItem('order', JSON.stringify(data));
  console.log(a + ':' + order[a]);

  var order = JSON.parse(localStorage.getItem('order'));
  console.log(typeof(order));
  for (a in order) {}

});


function storeOrder() {
  var pizzaqty = document.getElementById('qty_slice of pizza').value;
  localStorage.setItem('pizza', pizzaqty);
  var price = pizzaqty * 2;
}


function retrieveOrder() {
  var pizzaordered = localStorage.getItem('pizza');
}

//output html
//
//document.getElementById("menuOutput").innerHTML = "Here is the menu: <br>" + data.menu;
//why in't this working?

//style menu for ordering
//save order as json string
//save in local storage
//your order button

//onclick: show order   
document.getElementById('order').innerHTML = localStorage.getItem('order1');
<h1 class="menu">Menu</h1>
<div class="grid">
  <div class="two">
    <h2>Pizza by the slice ($2)</h2>
    <input type="number" id="qty_slice of pizza">
    <h2>Toppings</h2>
    <p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
    <p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
    <p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
    <p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
  </div>

  <div class="one">
    <h2>Sides</h2>
    <p class="titles">Potato Salad($1.25):</p> <input type="number" id="qty_potato salad">
    <p class="titles">Humus($2.50):</p> <input type="number" id="qty_hummus">
    <p class="titles">Caesar Salad($3.50):</p> <input type="number" id="qty_caesar salad">
    <p class="titles">Garden Salad($2.25):</p> <input type="number" id="qty_garden salad">
  </div>

  <div class="three">
    <h2>Drinks</h2>
    <div>

      <p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
      <p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
      <p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
    </div>
    <hr>
    <p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
    <p class="titles">Water($1.25):</p> <input type="number" id="qty_water">

  </div>
</div><br>
<div class="button">
  <button class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>
<script src="./run.js"></script>
javascript html css grid
1个回答
0
投票

这里是开始。

您可以进行更优雅的递归,但这比一些非干燥代码要难得多

您将需要添加复选框和/或数量字段

完成后,需要在字段上使用addEventListener(“ input”)

然后您需要循环/映射输入的内容并使用JSON.stringify(“ order”,order)并在装入事件处理程序中将其取反

const getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('get', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status == 200) {
      callback(null, xhr.response);
    } else {
      callback(status);
    }
  };
  xhr.send();
};

const fNum = str => {
  str = str.trim()
  return str && !isNaN(str) ? "$" + Number(str).toFixed(2) : str;
};



getJSON('https://mm214.com/menu.php', function(err, data) {
  // console.log(data)
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {
    const container = document.getElementById("menuOutput");
    const menu = data.menu;
    Object.keys(menu).forEach(key => {
      const div = document.createElement("div");
      const header = document.createElement("h2");
      header.textContent = key
      div.appendChild(header)
      const sub = menu[key];
      if (typeof sub === 'object') {
        Object.keys(sub).forEach(subKey => {
          const subDiv = document.createElement("div")
          const subHeader = document.createElement("h3")
          subHeader.textContent = subKey;
          subDiv.appendChild(subHeader)
          const subsub = sub[subKey];
          if (typeof subsub === 'object') {
            Object.keys(subsub).forEach(subsubKey => {
              const p = document.createElement("p")
              p.textContent = subsubKey + ": " + fNum(subsub[subsubKey]);
              subDiv.appendChild(p)
            });
          } else {
            subHeader.appendChild(document.createTextNode(": " + fNum(subsub)))
          }

          div.appendChild(subDiv)
        })
      } else {
        header.appendChild(document.createTextNode(": " + fNum(sub)))
      }

      container.appendChild(div)
    })

  } //closes outer for loop

  //localStorage only stores strings! Stringify turns objects into strings!
  //parse converts JSON strings to objects that can be looped around

  // document.getElementById("menuOutput").innerHTML = content;
  // localStorage.setItem('order', JSON.stringify(data));
  // console.log(a + ':' + order[a]);

  //  var order = JSON.parse(localStorage.getItem('order'));
  //  console.log(typeof(order));
  // for (a in order) {}

});



//style menu for ordering
//save order as json string
//save in local storage
//your order button

//onclick: show order	
//document.getElementById('order').innerHTML = localStorage.getItem('order1');
h2,
h3 {
  text-transform: capitalize
}
<h1 class="menu">Menu</h1>
<div class="grid">
  <!-- div class="two">
    <h2>Pizza by the slice ($2)</h2>
    <input type="number" id="qty_slice of pizza">
    <h2>Toppings</h2>
    <p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
    <p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
    <p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
    <p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
  </div>

  <div class="one">
    <h2>Sides</h2>
    <p class="titles">Potato Salad($1.25):</p> <input type="number" id="qty_potato salad">
    <p class="titles">Humus($2.50):</p> <input type="number" id="qty_hummus">
    <p class="titles">Caesar Salad($3.50):</p> <input type="number" id="qty_caesar salad">
    <p class="titles">Garden Salad($2.25):</p> <input type="number" id="qty_garden salad">
  </div>

  <div class="three">
    <h2>Drinks</h2>
    <div>

      <p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
      <p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
      <p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
    </div>
    <hr>
    <p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
    <p class="titles">Water($1.25):</p> <input type="number" id="qty_water">

  </div-->
</div><br>
<div class="button">
  <button class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>
<div id="menuOutput"></div>
© www.soinside.com 2019 - 2024. All rights reserved.