使用getJSON中的每个函数返回undefined

时间:2015-01-02 22:57:54

标签: javascript jquery json getjson

我正在使用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
                }
            ]

        }

    ]


}

我认为错误可能在我的每个功能中,但我还没能识别它。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

你的锻炼工作是一个数组,需要另一个循环

$.each( data.exercises, function ( index, exercise ) {
    $.each(exercise.work, function (index, work) {
         console.log(work);
    });
});

答案 1 :(得分:1)

此:

output += '<li>' + exercise.work.weight + ' x ' + exercise.work.reps  + '</li>';

假设您的JSON如下:

"exercises" : [
  {
    "name" : "Squats",
    "work" : 
      {
        "weight" : 135,
        "reps" : 5
      }
  },

实际上work实际上是一个数组。

你想要这样的东西:

$.each( data.exercises, function ( index, exercise ) {

   $.each( exercise.work, function( index, workout ) { 
      output += '<li>' + workout.weight + ' x ' + workout.reps  + '</li>';
   });

});
相关问题