简体   繁体   English

将 JSON object 从一个 Javascript 文件导入到另一个

[英]Import JSON object to from one Javascript file to another

I am creating a simple Online Grocery Sotre.我正在创建一个简单的 Online Grocery Sotre。 I have one HTML file that the user uses to select the items and amounts they want.我有一个 HTML 文件,用户用于 select 他们想要的项目和金额。 The HTML file has a javascript file associated that takes the values input by the user and places it into an array. HTML 文件具有关联的 javascript 文件,该文件获取用户输入的值并将其放入数组中。 This works fine.这工作正常。

My Goal -> is to then use the json object created and display it or use it in another html file that I will use to display the users order.我的目标 -> 然后使用创建的 json object 并显示它或在另一个 html 文件中使用它来显示用户订单。 I am have tried different way to do this but I can't import the json object created.我尝试了不同的方法来做到这一点,但我无法导入创建的 json object。

HTML FORM HTML 表格

  </div>

      <div class="row">
                <div class="column">
                    <img src="images/vegetables.jpg" alt="vegetables" width="250" height="166"><br>
                    <select name="veggies" id="veggies">
                    <option value="none">None</option>
                    <option value="carrot">Carrot</option>
                    <option value="tomato">Tomato</option>
                    <option value="potato">Potato</option>
                    <option value="pepper">pepper</option>
                    </select>
                    <input type="number" id="quantity1" name="quantity1" min="1" max="5">
                </div>
                <div class="column">
                    <img src="images/meats.jpg" alt="meats" width="250" height="166"><br>
                    <select name="meats" id="meats">
                    <option value="none">None</option>
                    <option value="chicken">Chicken</option>
                    <option value="beef">Beef</option>
                    <option value="pork">Pork</option>
                    <option value="fish">fish</option>
                    </select>
                    <input type="number" id="quantity2" name="quantity2" min="1" max="5">
                </div>
                <div class="column">
                    <img src="images/breads.jpg" alt="breads" width="250" height="166"><br>
                    <select name="breads" id="breads">
                    <option value="none">None</option>
                    <option value="whiteBread">White Bread</option>
                    <option value="WheatBread">Wheat Bread</option>
                    <option value="baguette">Baguette</option>
                    <option value="cake">Cake</option>
                    </select>
                    <input type="number" id="quantity3" name="quantity3" min="1" max="5">
                </div>
                <div class="column">
                    <img src="images/sweets.jpg" alt="sweets" width="250" height="166"><br>
                    <select name="sweets" id="sweets">
                    <option value="none">None</option>
                    <option value="chocolate">Chocolate</option>
                    <option value="candy">Candy</option>
                    <option value="cookies">Cookies</option>
                    <option value="IceCream">Ice Cream</option>
                    </select>
                    <input type="number" id="quantity4" name="quantity4" min="1" max="5">
                </div>
                <div class="column">
                    <img src="images/softDrinks.jpg" alt="softDrinks" width="250" height="166"><br>
                    <select name="drinks" id="drinks">
                    <option value="none">None</option>
                    <option value="coke">Coke</option>
                    <option value="pepsi">Pepsi</option>
                    <option value="7up">7-Up</option>
                    <option value="iceTea">Ice Tea</option>
                    </select>
                    <input type="number" id="quantity5" name="quantity5" min="1" max="5">
                </div>
                <div class="column">
                    <img src="images/eggs.jpg" alt="eggs" width="250" height="166"><br>
                    <select name="eggs" id="eggs">
                    <option value="none">None</option>
                    <option value="eggs">Eggs</option>
                    <option value="milk">Milk</option>
                    <option value="cheese">Cheese</option>
                    </select>
                    <input type="number" id="quantity6" name="quantity6" min="1" max="5">
                </div>

            </div>
            <br>
            <button type="submit" class="button button2" id="btn1" >Submit</button>

            <br><br><br>
            <br>

This is the js file associated to this HTML form that captures the values and creates the json object.这是与此 HTML 表单关联的 js 文件,该表单捕获值并创建 json object。

document.getElementById("btn1").onclick = function(){Purchase()}
document.getElementById("pay").onclick = function(){Cart()}


var products = new Array();
var amount = new Array();

function Purchase(){

    // veggies value and amount
    var veggies = document.getElementById('veggies').value 
    var veggiesAmount = document.getElementById('quantity1').value

    // meats value and amount
    var meats = document.getElementById('meats').value 
    var meatsAmount = document.getElementById('quantity2').value

    // breads value and amount 
    var breads = document.getElementById('breads').value 
    var breadsAmount = document.getElementById('quantity3').value

    // sweets value and amount 
    var sweets = document.getElementById('sweets').value 
    var sweetsAmount = document.getElementById('quantity4').value

    // soft drinks value and amount 
    var drinks = document.getElementById('drinks').value 
    var drinksAmount = document.getElementById('quantity5').value

    // eggs drinks value and amount 
    var eggs = document.getElementById('eggs').value 
    var eggsAmount = document.getElementById('quantity6').value

    // new elements to array
    products.push(veggies)
    amount.push(veggiesAmount)

    products.push(meats)
    amount.push(meatsAmount)

    products.push(breads)
    amount.push(breadsAmount)

    products.push(sweets)
    amount.push(sweetsAmount)

    products.push(drinks)
    amount.push(drinksAmount)

    products.push(eggs)
    amount.push(eggsAmount)
    
    
    console.log(products)
    console.log(amount)



}

When I run the file normal this is the image of what I get.当我正常运行文件时,这是我得到的图像。

JSON 对象

I want to display that json object on this HTML file.我想在这个 HTML 文件上显示 json object 。

展示形式

you don't have to get every element value, there is a more generic way to do that.您不必获取每个元素值,有一种更通用的方法可以做到这一点。 try that solution.试试那个解决方案。

SOLUTION.解决方案。 #1 #1

javascript snippet javascript 片段

document.getElementById("btn1").onclick = function () {
  purchase();
};

function getAllValues() {
  const ProductObject = [];
  let components = document.querySelectorAll(".column");
  let itemsList = Array.from(components);

  itemsList.forEach((item) => {
    let productName = item.getElementsByTagName("select")[0].value;
    let productAmount = item.getElementsByTagName("input")[0].value;
    if (productName !== "none") {
      ProductObject.push({
        name: productName,
        amount: productAmount
      });
    }
  });

  return ProductObject;
}

function purchase() {
  let selectedProducts = getAllValues();
  
  let table = document.querySelector("#product_table");
  let tbody = document.querySelector("#product_table tbody");
  let tableBody = document.createElement("tbody");
  let htmlList = [];

  // reset table before update.
  tbody && table.removeChild(tbody);

  Object.values(selectedProducts).forEach((product) => {
    htmlList.push(
      `<tr>
        <td> ${product.name} </td>
        <td> ${product.amount} </td>
      </tr>`
    );
  });

  tableBody.innerHTML = htmlList.join("");
  table.appendChild(tableBody);
}

SOLUTION.解决方案。 #2 #2

document.getElementById("btn1").onclick = function () {
  purchase();
};

[...document.querySelectorAll('input[type="number"]')].forEach((i) =>
  i.setAttribute("disabled", true)
);

let selectedProducts = {};

let productForm = document.getElementById("ProductForm");
productForm.addEventListener("change", updateProducts);

function updateProducts(event) {
  let productType = event.target.name;

  if (event.target.type === "number") {
    let currentProduct = event.target.previousElementSibling.name;

    selectedProducts[currentProduct] = {
      ...selectedProducts[currentProduct],
      amount: event.target.value
    };
  } else {
    let siblingInput = event.target.nextElementSibling;
    siblingInput.removeAttribute("disabled");
    selectedProducts[productType] = {
      amount: "",
      name: event.target.value
    };
  }
}

function purchase() {
  let table = document.querySelector("#product_table");
  let tbody = document.querySelector("#product_table tbody");
  let tableBody = document.createElement("tbody");
  let htmlList = [];

  // reset table before update.
  tbody && table.removeChild(tbody);

  Object.values(selectedProducts).forEach((product) => {
    htmlList.push(
      `<tr>
        <td> ${product.name} </td>
        <td> ${product.amount} </td>
      </tr>`
    );
  });

  tableBody.innerHTML = htmlList.join("");
  table.appendChild(tableBody);
}

and for the HTML snippet add an id to the parent of the controls.对于 HTML 片段,将id添加到控件的父级。 to capture the event propagation.捕获事件传播。

<body>
    <div class="row" id="ProductForm"> // id="ProductForm"
      <div class="column">
         .....

live working demo 现场工作演示

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

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