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条)

报告相同问题?

悬赏问题

  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换