簡體   English   中英

使用 JavaScript 將 JSON 數據顯示到 HTML 頁面

[英]Display JSON data to HTML page using JavaScript

第一次接觸 JSON,所以請像我 5 歲一樣解釋一下,沒有行話。 我收到了一個這樣的 JSON 文件,需要在 HTML 列表中顯示這些項目。 很多示例都將 JSON 對象分配給了一個變量——它沒有分配給一個變量,所以我不確定如何引用它。 如何訪問和顯示產品列表中的所有內容。 在我的 html 中,我鏈接到了一個 script.js 文件和這個 json 文件。

HTML

  <h1>My Cart</h1>
    <div id="cart">
        <h2>Cart Items</h2>
        <ul id="cartItemsList">
        </ul>
    </div>

JSON

    "basket": {
        "productList": [{
            "product": {
                "id": "111",
                "name": "Dog",
                "shortDescription": "<p>Mans best friend</p>",
                },
                "category": "Canine",
                "availability": "In Stock",
                "variationType": {
                    "name": "Breed",
                    "value": "Collie"
                }
            },
            "quantity": 1,
            "price": "$53.00"
        }, {
            "product": {
                "id": "112",
                "name": "Dog",
                "shortDescription": "<p>Not so best friend</p>",
                "category": "feline",
                "availability": "Low In Stock",
                "variationType": {
                    "name": "breed",
                    "value": "Maine Coon"
                }
            },
            "quantity": 1,
            "price": "$49.00"
        }, {
            "product": {
                "id": "113",
                "name": "Rabbit",
                "shortDescription": "Likes carrots",
                "category": "cuniculus",
                "availability": "In Stock"
            },
            "quantity": 1,
            "price": "$66.00"
        }]
    }

JavaScript

    var products = document.getElementById("cartItemsList");
    cartItemsList.innerHTML = "<li>" + product + "</li>";

如果您從外部文件加載它,您將需要 Ajax 或類似類型的調用。 要使用 Ajax,您必須向項目的 HTML 文件中添加一個名為 jQuery 的庫。 然后,您可以調用您的 JSON,而無需將其作為 javascript 變量引用,如您在以下工作代碼片段中所見。

 /* I put your JSON into an external file, loaded from github */ var url = "https://raw.githubusercontent.com/mspanish/playground/master/jessica.json"; /* this tells the page to wait until jQuery has loaded, so you can use the Ajax call */ $(document).ready(function(){ $.ajax({ url: url, dataType: 'json', error: function(){ console.log('JSON FAILED for data'); }, success:function(results){ /* the results is your json, you can reference the elements directly by using it here, without creating any additional variables */ var cartItemsList = document.getElementById("cartItemsList"); results.basket.productList.forEach(function(element) { cartItemsList.insertAdjacentHTML( 'beforeend',"<li>" + element.product.name + " : " + element.price+ " </li>"); }); // end of forEach } // end of success fn }) // end of Ajax call }) // end of $(document).ready() function
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>My Cart</h1> <div id="cart"> <h2>Cart Items</h2> <ul id="cartItemsList"> </ul> </div>

如果你想解析一個對象:

function logTheObj(obj) {
    var ret = "";
    for (var o in obj) {
        var data = obj[o];
        if (typeof data !== 'object') {
            ret += "<li>" + o + " : " + data + "</li>";
        } else {
            ret += "<li>" + o + " : " + logTheObj(data) + "</li>";
        }
    }
    return "<ul>" + ret + "</ul>";
}

如果您的對象在字符串中:

logTheObj(JSON.parse(jsonString));

首先,您必須將json從長字符串轉換為尖銳的 js 對象。 您可以通過JSON.parse命令執行此操作。 像這樣:

let jsObj = JSON.parse( youreJsonString);

他們,您可以循環將您的產品扔到您的產品列表中並構建您的 html 代碼,如下所示:

var products = document.getElementById("cartItemsList");

jsObj.basket.productList.forEach( function(product ) {
        cartItemsList.innerHTML = "<li>" + product.name + " : " + product.price+ " </li>";
});

除非您使用 Ajax 調用或類似的方法來加載外部 JSON,否則您需要將您提供的 JSON 轉換為可以作為變量引用的對象。 此外,您的 JSON 無效。 我嘗試在這里更正它,並將您的 JSON 引用為一個對象,您可以通過名為obj的變量引用。 這是一個工作代碼片段。

 var obj = { "basket": { "productList": [{ "product": { "id": "111", "name": "Dog", "shortDescription": "<p>Mans best friend</p>", "category": "Canine", "availability": "In Stock", "variationType": { "name": "Breed", "value": "Collie" } }, "quantity": 1, "price": "$53.00" }, { "product": { "id": "112", "name": "Dog", "shortDescription": "<p>Not so best friend</p>", "category": "feline", "availability": "Low In Stock", "variationType": { "name": "breed", "value": "Maine Coon" } }, "quantity": 1, "price": "$49.00" }, { "product": { "id": "113", "name": "Rabbit", "shortDescription": "Likes carrots", "category": "cuniculus", "availability": "In Stock" }, "quantity": 1, "price": "$66.00" }] } } var cartItemsList = document.getElementById("cartItemsList"); obj.basket.productList.forEach(function(element) { cartItemsList.insertAdjacentHTML( 'beforeend',"<li>" + element.product.name + " : " + element.price+ " </li>"); });
 <h1>My Cart</h1> <div id="cart"> <h2>Cart Items</h2> <ul id="cartItemsList"> </ul> </div>

Javascript Ajax 版本使用 Stacey Reiman 先前回答中的外部 json 文件

 const products = document.getElementById("cartItemsList"); /* get basket items from JSON */ class Basket { async cartItems() { try { let result = await fetch('https://raw.githubusercontent.com/mspanish/playground/master/jessica.json') let data = await result.json() // return data /* destructuring data */ let basketItems = data.basket.productList basketItems = basketItems.map(item =>{ const price = item.price const{id,name,shortDescription,category,availability} = item.product const breed = item.product.variationType const quantity = item.quantity return {price,id,name,shortDescription,category,availability,quantity,breed} }) return basketItems } catch (error) { console.log(error) } } } /* Display stuff from the basket */ class Display { displayBasket(basket) { //console.log(basket) let result = "" basket.forEach((item)=>{ result += ` <li> id : ${item.id} name: ${item.name} price: ${item.price} availability: ${item.availability} category : ${item.category} quantity : ${item.quantity} shortDescription : ${item.shortDescription} </li> `}) cartItemsList.innerHTML = result } } document.addEventListener("DOMContentLoaded", ()=>{ const basket = new Basket() const display = new Display() basket.cartItems().then(basket => display.displayBasket(basket)) })
 <h1>My Cart</h1> <div id="cart"> <h2>Cart Items</h2> <ul id="cartItemsList"> </ul> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM