[英]Using the each function within getJSON returns undefined
I'm using jQuery's getJSON method to retrive and parse a simple JSON file, but when I output the values onto my page it's displaying as undefined
我正在使用jQuery的getJSON方法来检索和解析一个简单的JSON文件,但是当我将值输出到页面上时,它显示为
undefined
$.getJSON( 'js/example.json', function ( data ) {
var output = '';
$.each( data.exercises, function ( index, exercise ) {
output += '<li>' + exercise.work.weight + ' x ' + exercise.work.reps + '</li>';
});
$( '#example' ).html( output );
});
example.json
{
"exercises" : [
{
"name" : "Squats",
"work" : [
{
"weight" : 135,
"reps" : 5
},
{
"weight" : 225,
"reps" : 5
},
{
"weight" : 315,
"reps" : 5
}
]
},
{
"name" : "Bench",
"work" : [
{
"weight" : 135,
"reps" : 5
},
{
"weight" : 225,
"reps" : 5
},
{
"weight" : 315,
"reps" : 5
}
]
},
{
"name" : "Rows",
"work" : [
{
"weight" : 135,
"reps" : 5
},
{
"weight" : 225,
"reps" : 5
},
{
"weight" : 315,
"reps" : 5
}
]
}
]
}
I think the error might lie within my each function, but I haven't been able to identify it yet. 我认为错误可能出在我的每个函数中,但我还无法识别出它。 Any ideas?
有任何想法吗?
Your exercise work is an array, need another loop 您的锻炼工作是一个数组,需要另一个循环
$.each( data.exercises, function ( index, exercise ) {
$.each(exercise.work, function (index, work) {
console.log(work);
});
});
This: 这个:
output += '<li>' + exercise.work.weight + ' x ' + exercise.work.reps + '</li>';
assumes your JSON looks like: 假设您的JSON如下所示:
"exercises" : [
{
"name" : "Squats",
"work" :
{
"weight" : 135,
"reps" : 5
}
},
When in fact work
is an array in each case. 实际上,在每种情况下,
work
都是一个数组。
You want something like: 您想要类似的东西:
$.each( data.exercises, function ( index, exercise ) {
$.each( exercise.work, function( index, workout ) {
output += '<li>' + workout.weight + ' x ' + workout.reps + '</li>';
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.