我有一个HTML表格,我想用JSON对象填充它。打印对象有效,但我无法单独获取阵列。当我试图获得一种成分的价值时,它一直说未定义。我的代码有什么问题?
JQ:
function loadIngredients() {
$.get("js/test.json", (data) => {
console.log(data);
$.each(data, function (index) {
console.log(this.ingredient);
});
});
}
JSON:
{
"data":[
{"ingredient":"Banaan", "hoeveelheid":"50", "energie":"89", "vet":"0,9", "verzagigd vet":"0,3", "eiwit":"1,2", "koolhydraten":"20,4", "vezels":"1,9", "zout":"0,0"},
{"ingredient":"Appel", "hoeveelheid":"80", "energie":"77", "vet":"0,6", "verzagigd vet":"0,1", "eiwit":"1,1", "koolhydraten":"15,6", "vezels":"2,5", "zout":"0,1"},
{"ingredient":"Brood", "hoeveelheid":"120", "energie":"320", "vet":"1,1", "verzagigd vet":"0,4", "eiwit":"7,4", "koolhydraten":"30,6", "vezels":"4,8", "zout":"0,8"}
]
}
答案 0 :(得分:1)
$.each
循环中的“数据”不是包含{}
的变量。尝试使用data.data
$.each(data.data, function(index) {
console.log(this.ingredient);
});
var data = {
"data": [{
"ingredient": "Banaan",
"hoeveelheid": "50",
"energie": "89",
"vet": "0,9",
"verzagigd vet": "0,3",
"eiwit": "1,2",
"koolhydraten": "20,4",
"vezels": "1,9",
"zout": "0,0"
},
{
"ingredient": "Appel",
"hoeveelheid": "80",
"energie": "77",
"vet": "0,6",
"verzagigd vet": "0,1",
"eiwit": "1,1",
"koolhydraten": "15,6",
"vezels": "2,5",
"zout": "0,1"
},
{
"ingredient": "Brood",
"hoeveelheid": "120",
"energie": "320",
"vet": "1,1",
"verzagigd vet": "0,4",
"eiwit": "7,4",
"koolhydraten": "30,6",
"vezels": "4,8",
"zout": "0,8"
}
]
}
function loadIngredients() {
$.each(data.data, function(index) {
console.log(this.ingredient);
});
}
loadIngredients();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>