dth981485742 2015-01-14 00:51
浏览 57
已采纳

从PHP中回显的json编码数组中迭代javascript对象

I'm trying to get values from a PHP array in Javascript and populate a chart.

The problem is I believe that the javascript variable is not receiving the values.

I tried printing out the values, but nothing happens. Also it shows as object instead of an array, i don't know if it's suppose to be like that.

Any help will be greatful.

The PHP array when printed out:

print_r("<pre>"); 
print_r($exam_grades);
print_r("</pre>");

Array
(
    [History] => 70
    [Sociology] => 40
    [Psychology] => 32
    [Criminology] => 64
)

JS:

var exam_grades = <?php echo json_encode($exam_grades );?>;
alert(exam_grades.length); // this shows as undefined
for (var i = 0; i < exam_grades.length; i++) {

    // do something      
}
  • 写回答

4条回答 默认 最新

  • doubengman2072 2015-01-14 01:01
    关注

    As an alternative, you could also use for in to iterate thru the object:

    <?php $exam_grades = array('History' => 70, 'Sociology' => 40, 'Psychology' => 32, 'Criminology' => 64); ?>
    <script type="text/javascript">
    var exam_grades = <?php echo json_encode($exam_grades); ?>;
    for(var key in exam_grades) {
        var value = exam_grades[key];
        console.log(key + ': ' + value);
    }
    </script>
    

    Sample Output

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?