3

PHP - This is part of a Highchart configuration array that is returned by a PHP function (which is json_encoded)

'plotOptions' => array(
    'pie' => array(
        'allowPointSelect'  => TRUE,
        'cursor'            => 'pointer',
        'dataLabels'        => array(
            'enabled'           => TRUE,
            'color'             => '#000000',
            'connectorColor'    => '#000000',
            'formatter'         => "function() { return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %' }"
        )
    )
)

JavaScript - Accessing this information from the encoded data

container.highcharts(r.hc);
// r.hc is the array that contains the highchart information above

The problem I'm having is:

Uncaught TypeError: Object function() { return '<b>'+ this.point.name +'</b>: '+
this.percentage +' %' } has no method 'call'

How do I change this so it recognizes it as a function? Or is this even possible?

4

2 回答 2

2

从远程源执行 javascript 是个坏主意,因为您不能信任它。但是,如果您必须:

json 中包含的函数是一个字符串,因此您需要对其进行评估:

 pie.dataLabels.formatter = eval('('+pie.dataLabels.formatter+')');

对于需要转换的对象的每个方法。

但是,正如开头所说,几乎可以肯定有一个解决方案不需要您以这种方式获取 javascript。

于 2013-05-22T18:40:41.303 回答
0

我决定只返回饼图 highchart 的系列数据......而不是整个 highchart 配置数组...... plotOptions 现在在 javascript 中定义,而不是由 json_encoded PHP 数组返回......

我不太确定我为什么要这样做,但感谢对 eval 的所有帮助!

于 2013-05-28T16:32:38.277 回答