【问题标题】:passing formatting JavaScript code to HighCharts with JSON使用 JSON 将格式化 JavaScript 代码传递给 HighCharts
【发布时间】:2014-10-20 17:59:42
【问题描述】:

我有一个使用 AJAX 将 JSON 格式的字符串传送到 HighCharts 图表的网站。

您可以将其视为中间 JSON 代码部分:

http://jsfiddle.net/1Loag7pv/

$('#container').highcharts(

//JSON Start

{
"plotOptions": {
"series": {"animation": {"duration": 500}}
,"pie": {
"allowPointSelect": true,
"cursor": "pointer",
"dataLabels": {"formatter":function(){return this.point.name+': '+this.percentage.toFixed(1) + '%';}}
    }
},
"chart":{"renderTo":"divReportChart"}
,"title":{"text":"Sales Totals"}
,"xAxis":{"title":{"text":"Item"}, "categories":["Taxes","Discounts","NetSalesTotal"], "gridLineWidth":1}
,"yAxis":[{"title":{"text":"Amount"}, "gridLineWidth":1}]
,"series":[{"name":"Amount","type":"pie", "startAngle": -60,"yAxis": 0,"data":[["Taxes",17.8700],["Discounts",36.0000],["NetSalesTotal",377.9500]]}]
}

 //JSON end

);

问题在于功能部分...

"dataLabels": {"formatter":function(){return this.point.name+': '+this.percentage.toFixed(1) + '%';}}

没有通过 JSON 传输

所有研究都告诉我没有办法做到这一点。

IE...Is it valid to define functions in JSON results?

有人知道如何绕过这个限制吗?

【问题讨论】:

  • 对不起;我看错了介绍。的确,您不能通过 JSON 发送函数,但没有什么能阻止您在调用 Highcharts 之前在客户端中添加这些函数。
  • 为什么要通过 AJAX 将 Highcharts 选项发送到服务器? Highcharts 是一个客户端绘图库,您的服务器将如何处理配置?

标签: javascript ajax json highcharts


【解决方案1】:

您不能在 JSON 中传递函数。 Javascript 是 JSON 的超集。

一种常见的方法是在 javascript 中定义图表(例如在页面加载期间),然后页面通过 Ajax 仅请求数据。返回数据后,可以在渲染之前或之后使用 highcharts API 将其添加到图表对象中。

如果你真的想用图表从服务器传递格式化程序函数,把它作为一个字符串发送,然后把它变成这样的函数:

var fn = Function(mystring);

并在高图表中使用它,例如:

chart.plotOptions.pie.dataLabels = {"formatter":fn};

我重新考虑了您的示例以显示该方法:http://jsfiddle.net/wo7zn0bw/

【讨论】:

    【解决方案2】:

    我也有类似的难题。我想创建 JSON 服务器端(ruby on rails),这样我就可以为 Web API 创建图表图像,并使用相同的代码将其呈现在客户端 Web 浏览器上。这类似于 SteveP 的回答。

    为了符合 JSON 标准,我将所有格式化程序函数都更改为字符串

    {"formatter": "function(){ return this.point.name+':'+this.percentage.toFixed(1) + '%';}"}
    

    在 Web 端,我浏览哈希以查找格式化程序键并将它们替换为使用此代码的函数(可能是更好的方法!?)。 javascript

    function HashNavigator(){
    
        this.navigateAndReplace = function(hash, key){
            if (!this.isObject(hash)){
                //Nice if only navigated hashes and arrays
                return;
            }
    
            var keys = Object.keys(hash);
            for(var i = 0; i< keys.length; i++){
                if (keys[i] == key){
                    //convert string to js function
                    hash[keys[i]] = this.parseFunction(hash[keys[i]]);
                } else if (this.isObject(hash[keys[i]])){
                    //navigate hash tree
                    this.navigateAndReplace(hash[keys[i]], key);
                } else {
                    //continue
                }
            }
        };
    
        this.isObject = function(testVar) {
            return testVar !== null && typeof testVar === 'object'
        }
    
        //http://stackoverflow.com/questions/7650071/is-there-a-way-to-create-a-function-from-a-string-with-javascript
        this.parseFunction = function(fstring){
            var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
            var match = funcReg.exec(fstring.replace(/\n/g, ' '));
    
            if(match) {
                return new Function(match[1].split(','), match[2]);
            }
    
            return null;
        };
    
    }
    

    要使用它,将类似于此 javascript:

    hashNavigator = new HashNavigator();
    hashNavigator.navigateAndReplace(myHighchartsHash, "formatter")
    

    此时哈希/js-object 已准备好 Highcharts

    类似的想法被用于网络图像 API。

    我真的希望对 JSON 进行黑客攻击不是唯一的解决方案,但它确实有效!

    【讨论】:

      【解决方案3】:

      我使用了不同的方法。我创建了一个如下所示的 JSON

      {"formatter": "function(){ return this.point.name+':'+this.percentage.toFixed(1) + '%';}"}
      

      当我来评估表达式时,我使用了(假设'formatter'的值是formatterValueString

      formatterValueString = formatterValueString.replace('function()', '');
      let opts = (new Function(formatterValueString)).call(this);
      formatterValue = opts;
      

      使用这种方法的原因是很难将“this”与函数绑定。 eval() 函数不能很好地访问变量 this。我相信有办法做到这一点。只是觉得这很快。

      【讨论】:

        猜你喜欢
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        • 2019-12-24
        • 2018-01-09
        • 1970-01-01
        • 1970-01-01
        • 2018-02-13
        • 2013-08-23
        相关资源
        最近更新 更多