使用JavaScript将JSON数据显示到HTML页面

问题描述 投票:0回答:3

第一次接触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>";
javascript json
3个回答
2
投票

如果从外部文件加载它,则需要Ajax或类似的调用。要使用Ajax,您必须将一个名为jQuery的库添加到项目的HTML文件中。然后,您可以调用您的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>

0
投票

首先,你必须将json从长字符串转换为锐利的js对象。你是通过JSON.parse命令这样做的。像这样:

let jsObj = JSON.parse( youreJsonString);

他们,你可以循环抛出你的productList中的产品并构建你的html代码,如下所示:

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

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

0
投票

除非您使用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>
© www.soinside.com 2019 - 2024. All rights reserved.