douyigua5381 2018-01-20 23:29
浏览 176
已采纳

json数据不返回值

I'm currently trying to "foreach" some json data, but console is not returning anything, while it should return values (integers) of progress bars.

My current PHP file that should return the json data

$jsonData = [
    'progress' => [
        'health_pc' => $my->hp_percent,
        'energy_pc' => $my->energy_percent,
        'awake_pc'  => $my->awake_percent,
        'nerve_pc'  => $my->nerve_percent,
        'exp_pc'    => $my->exp_percent,
    ]
];

echo json_encode($jsonData);

How I handle it in javascript:

// Progress Bars
            $.each(jsonData.progress, function() {
                $.each(this, function(k, v) {
                    console.log(k + '-' + v);
                });
            });    

Note that the console.log() doesn't log anything.

What i'm trying to achieve is to adjust the progress bars when the %'s change, normally I would do:

$('#health_pc').css('width', jsonData.progress.health_pc + '%');
$('#energy_pc').css('width', jsonData.progress.energy_pc + '%');
$('#awake_pc').css('width', jsonData.progress.awake_pc + '%');
$('#nerve_pc').css('width', jsonData.progress.nerve_pc + '%');
$('#exp_pc').css('width', jsonData.progress.exp_pc + '%');

but I want to foreach this rather than writing this all out.

Any help would be greatly appreciated.

Edit 1 Output of json_encode()

{"progress":{"health_pc":100,"energy_pc":100,"awake_pc":100,"nerve_pc":100,"exp_pc":3}}
  • 写回答

3条回答 默认 最新

  • douan3414 2018-01-20 23:41
    关注

    As long as the php variables are no arrays themselves one level of for each should be enough:

    $.each(jsonData.progress, function(k, v) {
         $('#'+k).css('width', v + '%');
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?