简体   繁体   English

如何将本地 json 文件渲染到 HTML 和浏览器中

[英]How to render local json file into HTML and browser

I am pretty new in Javascript and I have problem.我是 Javascript 的新手,我有问题。 Currently I am working on project, that is actually my practice project and I'm trying to make shopping cart page.目前我正在做项目,这实际上是我的实践项目,我正在尝试制作购物车页面。 My problem is with JSON file, I don't know how to render it (show it within HTML in browser), I have local JSON file with some products.我的问题是 JSON 文件,我不知道如何渲染它(在浏览器中的 HTML 中显示它),我有一些产品的本地 JSON 文件。 Here is my code of main page, app.js(where is my function for JSON file) and JSON file with products这是我的主页代码,app.js(JSON 文件的 function 文件在哪里)和 JSON 文件与产品

HTML file 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 file 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();

and JSON file which is called products.json和 JSON 文件,称为 products.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"
      }
    }
  ]
}

So my question is what should I write in HTML file so I could get let's say name of product from JSON file into my div which is declared in HTML file for name or am I missing some more JS functions?所以我的问题是我应该在 HTML 文件中写什么,这样我就可以将 JSON 文件中的产品名称放入我的 div 中,该 div 是在 HTML 文件中声明的名称或函数? Currently my page is blank because I couldn't resolve how to get everything from JSON file.目前我的页面是空白的,因为我无法解决如何从 JSON 文件中获取所有内容。

HTML files are in views folder, app.js and products.json are outside of views folder. HTML 文件位于views 文件夹中,app.js 和products.json 位于views 文件夹之外。

Thanks!谢谢!

Try using a function to generate the template and set the innerHTML property.尝试使用 function 生成模板并设置innerHTML属性。

You can use this populateProducts function once you have got the response JSON from the API.从 API 获得响应JSON后,您可以使用此populateProducts function。 This will generate the template and will update the DOM.这将生成模板并更新 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>

If you're able to use a templating system such as Handlebars.js , you could convert the repeated part of your HTML (the item div) into a template and then populate it with the data.如果您能够使用诸如Handlebars.js之类的模板系统,您可以将 HTML(项目 div)的重复部分转换为模板,然后用数据填充它。 Adapting the 'Getting Started' example from the Handlebars page, the template would look something like:改编 Handlebars 页面中的“Getting Started”示例,模板如下所示:

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

Then in the script you would register the template:然后在脚本中注册模板:

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

...and then inside your HTTP request, you can pass the data to the template and it'll return HTML which you can add to the DOM as you wish: ...然后在您的 HTTP 请求中,您可以将数据传递给模板,它会返回 HTML 您可以根据需要将其添加到 DOM 中:

const html = template(context);

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

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