将json转换为变量

将json转换为变量

本文介绍了将json转换为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不会从数据库为jvectormap创建MapData,像这样

i wont create MapData for jvectormap from database,like this

{"AP":3,"DE":1,"GB":2,"ID":24,"US":10}

但是我的代码总是这样返回

but my code always return like this

["{\"AP\":3}","{\"DE\":1}","{\"GB\":2}","{\"ID\":24}","{\"US\":10}"]

这是我的javascript

this my javascript

    $(document).ready(function () {

    var mapData ={} 
               $.ajax({ url: '/orders/map', type: 'GET', dataType: 'json' }).success(function (data) {
               mapData = (data);
            });
    var dd =    JSON.stringify( mapData, null, '\t'); 


        $('#world-map').vectorMap({
            map: 'world_mill_en',

            regionStyle: {
                initial: {
                    fill: '#e4e4e4',
                    "fill-opacity": 1,
                    stroke: 'none',
                    "stroke-width": 0,
                    "stroke-opacity": 0
                }
            },
            series: {
                regions: [{
                    values: dd,
                    scale: ["#1ab394", "#22d6b1"],
                    normalizeFunction: 'polynomial'
                }]
            },
            onRegionTipShow: function (e, el, code) {
                console.log(dd[code]);
                    var mapcode = ( dd[code] ) ? ' ( ' + dd[code] + ' Visitor/Visitors  )' : ' ( No visitor yet! )';
                el.html(el.html() + mapcode );
            }
        });
    }); 

this my codeigniter controllers

        function map(){
        $rows = array();
        $query = $this->db->query('SELECT country, COUNT(1) AS rpt_count FROM vistors GROUP BY country');   
        foreach($query->result() as $row)
        {    
        $rows[] = '{"'.$row->country.'":'.$row->rpt_count.'}';
        }      

    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($rows));
        }

同志可以帮助我

推荐答案

您需要解析数据以获取可以从中获取数据的对象.

You need to parse the data to get an object you can get data from.

var mapData = JSON.parse(data);

这篇关于将json转换为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 17:07