如何从JSON文件中提取项目到HTML代码?

yhived7q  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(223)

我目前在从JSON文件拉东西到我的HTML页面方面遇到了麻烦。所以开始,我目前在JSON文件中有这个代码,这是我所有的项目(到目前为止),我想用一个项目来创建一个在线商店。
(EDIT:需要使其正确,因为这最初是一个Javascript文件。)

[
    {
        "id": 1,
        "productName": "Chutes and Ladders",
        "image": "../public/ChutesandLadders.jpg",
        "price": 15.75,
        "salePrice": 15.75
    },
    {
        "id": 2,
        "productName": "Monopoly",
        "image": "../public/Monopoly.jpg",
        "price": 15.25,
        "salePrice": 15.25
    },
    {
        "id": 3,
        "productName": "Clue",
        "image": "../public/Clue.jpg",
        "price": 20.00,
        "salePrice": 15.20
    },
    {
        "id": 4,
        "productName": "The Game of Life",
        "image": "../public/GameofLife.jpg",
        "price": 16.00,
        "salePrice": 10.00
    },
    {
        "id": 5,
        "productName": "TRESomme Shampoo",
        "image": "../public/Tresomme.jpg",
        "price": 45.00,
        "salePrice": 30.00
    },
    {
        "id": 6,
        "productName": "Michael Kors Purse",
        "image": "../public/MichaelKorsPurse.jpg",
        "price": 145.00,
        "salePrice": 145.00
    },
    {
        "id": 7,
        "productName": "Apple Watch Ultra",
        "image": "../public/AppleWatch.jpg",
        "price": 200.00,
        "salePrice": 175.00
    }
]

然后,为了显示它的一个示例,我在HTML页面(index.html)上有这些信息,我想将数据更改为JSON文件中的数据。

<div class="badge bg-dark text-white position-absolute" style="top: 0.5rem; right: 0.5rem">Sale</div>  
  <img class="card-img-top" width="450" height="200" src="Clue.jpg" alt="..." />         
     <div class="card-body p-4">
        <div class="text-center">
           <h5 class="fw-bolder">Clue</h5>
              <div class="d-flex justify-content-center small text-warning mb-2">
                 <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                 </div>
              <span class="text-muted text-decoration-line-through">$20.00</span>
              $15.20
           </div>
        </div>
        <div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
           <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="#">Add to cart</a></div>
        </div>
     </div>
  </div>

有没有一种方法可以将JSON数据导入到HTML文件中,在那里我可以真正做到这一点?

vcirk6k6

vcirk6k61#

以下是你可以采取的步骤。
1.确保你的JSON是imported/fetched等,并解析。
1.或者:
a)使用productName属性的值find对象,为该对象创建一些HTML,并将其附加到页面,或者
B)map在数组上,并为每个对象创建一些HTML。map返回一个数组,所以你会join它,然后将该HTML字符串附加到页面。
1.要创建HTML,最简单的方法是,因为您已经有了所需的标记,将其添加到template string中,并在其中的适当位置应用您希望显示的对象属性。
1.使用insertAdjacentHTML将HTML添加到页面。
1.使用Intl.NumberFormat可以创建格式正确的货币字符串。
下面是一个关于如何为一个对象(“Clue”)构建HTML并将其附加到页面的示例。所有的CSS都丢失了(显然),但我添加了一行来显示非销售价格的“line-through”。

const data=[{id:1,productName:"Chutes and Ladders",image:"../public/ChutesandLadders.jpg",price:15.75,salePrice:15.75},{id:2,productName:"Monopoly",image:"../public/Monopoly.jpg",price:15.25,salePrice:15.25},{id:3,productName:"Clue",image:"../public/Clue.jpg",price:20,salePrice:15.2},{id:4,productName:"The Game of Life",image:"../public/GameofLife.jpg",price:16,salePrice:10},{id:5,productName:"TRESomme Shampoo",image:"../public/Tresomme.jpg",price:45,salePrice:30},{id:6,productName:"Michael Kors Purse",image:"../public/MichaelKorsPurse.jpg",price:145,salePrice:145},{id:7,productName:"Apple Watch Ultra",image:"../public/AppleWatch.jpg",price:200,salePrice:175}];

// A function that accepts the array of data, a property
// name, and a query value, and returns the object that matches
// that condition
function finder(data, prop, query) {
  return data.find(obj => obj[prop] === query);
}

// A function to create properly a formatted
// currency string - pass in a number, a locale
// (e.g. 'en-GB'), and a currency type
function toCurrency(number, locale, type) {
  return new Intl.NumberFormat(locale, {
    style: 'currency',
    currency: type }
  ).format(number);
}

// Find the "Clue" object
const clue = finder(data, 'productName', 'Clue');

// Create the HTML using the object property values
// from the "Clue" object
const html = `
  <div class="badge bg-dark text-white position-absolute" style="top: 0.5rem; right: 0.5rem">Sale</div>  
  <img class="card-img-top" width="450" height="200" src="${clue.image}" alt="..." />         
     <div class="card-body p-4">
        <div class="text-center">
           <h5 class="fw-bolder">${clue.productName}</h5>
              <div class="d-flex justify-content-center small text-warning mb-2">
                 <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                 </div>
              <span class="text-muted text-decoration-line-through">${toCurrency(clue.price, 'en-GB', 'GBP')}</span>
              ${toCurrency(clue.salePrice, 'en-GB', 'GBP')}
           </div>
        </div>
        <div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
           <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="#">Add to cart</a></div>
        </div>
     </div>
  </div>
`;

// Append the HTML to the page
document.body.insertAdjacentHTML('beforeend', html);
.text-decoration-line-through { text-decoration: line-through; }
fjaof16o

fjaof16o2#

其中一种方法是使用fetch()API。

<script>
   fetch('data.json')
     .then(function(res){
         return res.json()
     })
     .then(function(data){
          return appendData(data)
      })
    function appendData(data){
        var con=document.getElementById("main-container")
        for(let i=0;i<data.length;i++){
            var d=document.createElement("div")
            d.textContent="Name: "+data[i].productName
            //add the data in whatever html element you want and then append it to the container
            con.appendChild(d);
        }
     }
</script>

希望这能帮上忙

相关问题