douzhi1937 2011-06-15 11:59
浏览 11

JavaScript和JSON

I am new to JS & JSON.I am struggle with converting JSON array to JavaScript array.How to do that? Here is my code:

var data = {
items: [
<? $i=1; foreach($query->result() as $row){ ?>
<? if($i!=1){ ?>,<? } ?>
{label: '<?=$row->district_name;?>', data: <?=$row->countid;?>}
<? $i++; } ?>
]
};

how to get the JSON array value to JavaScript Array. i just tried but it doesn't work. please some suggestions. here is my javascript array

for(i=0;i<5;i++){
chartData[i]=data.items[i].label+";"+data.items[i].data;

}
  • 写回答

3条回答 默认 最新

  • duanan6043 2011-06-15 12:12
    关注

    As the others already said, be careful when talking about JavaScript and JSON. You actually want to create a JavaScript object and not JSON.

    Don't mix PHP and JavaScript like this. It is horrible to maintain. Create an array beforehand, encode it as JSON* and print it:

    <?php
    
        $results = $query->result(); // get results
    
        function m($v) { // a helper function for `array_map`
            return array('label' => $v->district_name, 
                         'data' => $v->countid);
        }
    
        $data = array('items' => array_map('m', $results));
    
    ?>
    
    var data = <?php echo json_encode($data); ?>
    

    *: Here we use the fact that a JSON string is valid JavaScript too. You can just echo it directly in the JavaScript source code. When the JS code runs, it is not JSON, it is interpreted as JavaScript object.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'