从JSON编码的PHP传递JavaScript函数 [英] Passing a JavaScript function from JSON encoded PHP

查看:123
本文介绍了从JSON编码的PHP传递JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP - 这是由PHP函数返回的一个Highchart配置数组的一部分(这是json_encoded)

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



JavaScript - 从编码数据访问此信息

  container.highcharts(r.hc); 
// r.hc是包含
之上的高位图信息的数组>

问题I 'm have is:

  Uncaught TypeError:Object function(){return'< b> + this.point.name +'< / b>:'+ 
this.percentage +'%'}没有方法'调用'

我如何改变它以便将它识别为函数?或者,这甚至有可能?

解决方案

从远程源执行javascript是一个糟糕的主意,因为您不能相信它。但是,如果您必须:

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

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

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


$但是,正如开始所说,几乎肯定有一种解决方案,并不要求您以这种方式获取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?

解决方案

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.

这篇关于从JSON编码的PHP传递JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆