第一次接触 JSON,所以请像我 5 岁一样解释一下,不要使用行话。我收到了一个像这样的 JSON 文件,需要在 HTML 列表中显示这些项目。很多示例都将 JSON 对象分配给变量 - 这没有分配给变量,因此我不确定如何引用它。如何访问并显示产品列表中的所有内容。在我的 html 中,我链接到了 script.js 文件以及这个 json 文件。
超文本标记语言
<h1>My Cart</h1>
<div id="cart">
<h2>Cart Items</h2>
<ul id="cartItemsList">
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
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"
}]
}
Run Code Online (Sandbox Code Playgroud)
JavaScript
var products = document.getElementById("cartItemsList");
cartItemsList.innerHTML = "<li>" + product + "</li>";
Run Code Online (Sandbox Code Playgroud)
小智 6
如果您从外部文件加载此文件,则需要 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() functionRun Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)