douyanjing8287
douyanjing8287
2013-05-22 18:29

从JSON编码的PHP传递JavaScript函数

已采纳

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doudieyou5209 doudieyou5209 8年前

    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.

    点赞 评论 复制链接分享
  • duanping1632 duanping1632 8年前

    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!

    点赞 评论 复制链接分享

相关推荐