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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)