如何将本地json文件呈现为HTML和浏览器

时间:2019-11-20 12:41:24

标签: javascript html json

我在Java语言方面还很陌生,但遇到了问题。目前,我正在研究项目,这实际上是我的实践项目,并且正在尝试制作购物车页面。我的问题是JSON文件,我不知道如何呈现(在浏览器的HTML中显示),我有一些产品的本地JSON文件。这是我的主页代码,app.js(我的JSON文件的功能在哪里)和带有产品的JSON文件

HTML文件

<!DOCTYPE html>

<html lang="en">

<head>
  <title>Shopping Cart</title>

  <meta charset="utf-8" />
  <meta name="description" content="cobe" />
  <meta name="author" content="cobe" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="../style/style.css" />
</head>

<body>
  <main class="main-wrapper">

    <div class="items">
      <div class="item">
        <div class="image">
          <img src="" alt="" class="img">Image</img>
        </div>
        <h2 class="item-name">Name of item</h2>
        <h3 class="price">Price</h3>
        <button class="button">Add item</button>
      </div>
      <div id="products" class="list"></div>
    </div>
</main>

  <script type="text/javascript" src="../products.json"></script>
  <script type="text/javascript" src="../app.js"></script>

app.js文件

let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    let response = JSON.parse(xhttp.responseText);
    let products = response.products;

    let output = '';
    for (let i = 0; i < products.length; i++) {
      output += '<li>' + products[i].name + '</li>';
    }
    document.getElementById('products').innerHTML = output;
  }
};
xhttp.open("GET", "products.json", true);
xhttp.send();

和一个名为products.json的JSON文件

{
  "products": [
    {
      "id": 1,
      "name": "Eggs",
      "image": "https://d17zv3ray5yxvp.cloudfront.net/variants/W1ymDizfe679XsfX9uP8A5bU/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
      "price": {
        "amount": 7.99,
        "currency": "Kn",
        "measureUnit": "Kom"
      }
    },
    {
      "id": 2,
      "image": "https://d17zv3ray5yxvp.cloudfront.net/variants/b1qEMnNGbwiwV5cWysofPoqz/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
      "name": "Milk",
      "price": {
        "amount": 4.99,
        "currency": "Kn",
        "measureUnit": "Kom"
      }
    },
    {
      "id": 3,
      "image": "https://d17zv3ray5yxvp.cloudfront.net/variants/1avpwnxKAEqEpTf1k3VCbBbg/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
      "name": "Cheese",
      "price": {
        "amount": 44.99,
        "currency": "Kn",
        "measureUnit": "Kg"
      }
    }
  ]
}

所以我的问题是我应该在HTML文件中写些什么,以便让我们说产品名称从JSON文件到我的div中,该名称在HTML文件中声明为名称,还是我缺少更多的JS函数?目前我的页面为空白,因为我无法解析如何从JSON文件中获取所有内容。

HTML文件位于views文件夹中,app.js和products.json在views文件夹之外。

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试使用函数来生成模板并设置innerHTML属性。

从API获得响应populateProducts后,即可使用此JSON函数。这将生成模板并更新DOM。

var myData = {
  "products": [
    {
      "id": 1,
      "name": "Eggs",
      "image": "https://d17zv3ray5yxvp.cloudfront.net/variants/W1ymDizfe679XsfX9uP8A5bU/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
      "price": {
        "amount": 7.99,
        "currency": "Kn",
        "measureUnit": "Kom"
      }
    },
    {
      "id": 2,
      "image": "https://d17zv3ray5yxvp.cloudfront.net/variants/b1qEMnNGbwiwV5cWysofPoqz/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
      "name": "Milk",
      "price": {
        "amount": 4.99,
        "currency": "Kn",
        "measureUnit": "Kom"
      }
    },
    {
      "id": 3,
      "image": "https://d17zv3ray5yxvp.cloudfront.net/variants/1avpwnxKAEqEpTf1k3VCbBbg/7b27a910a7194c812eacf34700e38dcab3abed02f30837d1dad313c5651bb5fa",
      "name": "Cheese",
      "price": {
        "amount": 44.99,
        "currency": "Kn",
        "measureUnit": "Kg"
      }
    }
  ]
};

function populateProducts() {
  var template = '';
  for(let index = 0; index < myData.products.length; index++) {
    template += 
    "<div>Name: " + myData.products[index].name + "</div>" + 
    "<div>Image: <img class='my-image' src='" + myData.products[index].image + "' /></div>"+
    "<div>Amount: " + myData.products[index].price.amount + "</div>" + 
    "<div>Currency: " + myData.products[index].price.currency + "</div>" + 
    "<div>MeasureUnit: " + myData.products[index].price.measureUnit + "</div>";
  }
  document.getElementById('item-wrapper').innerHTML = template;
}

populateProducts();
.my-image {
  max-width: 50px;
}
<main class="main-wrapper">
  <div id="item-wrapper"></div>
</main>

答案 1 :(得分:0)

如果能够使用诸如Handlebars.js之类的模板系统,则可以将HTML的重复部分(项目div)转换为模板,然后用数据填充它。改编来自“把手”页面的“入门”示例,该模板将类似于:

<script id="item-template" type="text/x-handlebars-template">
  {{#each products}}
    <div class="item">
      <div class="image">
        <img src="{{image}}" alt="" class="img">Image</img>
      </div>
      <h2 class="item-name">{{name}}</h2>
      <h3 class="price">{{price.amount}}</h3>
      <button class="button">Add item</button>
    </div>
  {{/each}}
</script>

然后在脚本中注册模板:

const source = document.getElementById("item-template").innerHTML;
const template = Handlebars.compile(source);

...然后在HTTP请求中,您可以将数据传递到模板,它会返回HTML,您可以根据需要将其添加到DOM:

const html = template(context);