Passing a JavaScript function from JSON encoded PH

2019-05-10 01:21发布

问题:

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?

回答1:

Executing javascript from a remote source is a bad idea as you can't trust it. However, if you must:

The function included in the json is a string therefore you need to evaluate it:

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

for each method of the object that needs to be converted.

However, as said at the start, there is almost certainly a solution that does not require you to fetch javascript in this way.



回答2:

I've decided to only return series data for the pie highchart ... instead of the whole highchart configuration array ... plotOptions are now defined in javascript and not returned by a json_encoded PHP array ..

I'm not too sure why I was doing that but thanks for all the help with eval!