简体   繁体   English

无法将菜单从 php json 文件输出到 html

[英]Having trouble outputting the menu from a php json file to html

I was given a task which basically takes a json file and outputs the contents to a menu via javascript.我得到了一个任务,它基本上需要一个 json 文件并通过 javascript 将内容输出到菜单。 I have some code drawn out but it is not working.我提取了一些代码,但它不起作用。 The task needs to output the JSON file to html via api so that a customer can order.任务需要 output JSON 文件到 html 通过 Z8A5DA52ED126681DB398F14CE6DZ 客户可以订购4247D35AZE70A85。 Also it has to save the order as a JSON string to localstorage(browser).它还必须将订单作为 JSON 字符串保存到本地存储(浏览器)。 And finally it needs to basically spit out their order with the button (onClick).最后它需要用按钮(onClick)基本上吐出他们的订单。 So right now my problem is a.所以现在我的问题是。 when I add the id of "order" to the container div element my page goes white.当我将“订单”的 id 添加到容器 div 元素时,我的页面变为白色。 I dunno why that happens, but I would like to keep this format(design) if possible.我不知道为什么会这样,但如果可能的话,我想保留这种格式(设计)。 Secondly, well there is no second since output whites out my page lol.其次,没有第二个,因为 output 把我的页面变白了哈哈。 But I need to get past this first hurdle first.但我需要先克服这第一个障碍。 I will share my code (html, js, and css).我将分享我的代码(html、js 和 css)。 Any help or pointers would be appreciated!任何帮助或指示将不胜感激!

//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>

Here is a start.这是一个开始。

You could do a more elegant recurse, but that is much harder than a little non-dry code你可以做一个更优雅的递归,但这比一些非枯燥的代码要困难得多

You will need to add checkboxes and/or quantity fields您将需要添加复选框和/或数量字段

When you do, you need to use addEventListener("input") on the fields当你这样做时,你需要在字段上使用 addEventListener("input")

You then need to loop/map the content of the inputs and use JSON.stringify("order",order) and reverse that in the load event handler然后,您需要循环/映射输入的内容并使用 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM