javascript - 使用 JSON 将格式化 JavaScript 代码传递给 HighCharts

标签 javascript ajax json highcharts

我有一个网站使用 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 中传递函数。 Javascript 是 JSON 的超集。

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

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

var fn = Function(mystring);

并在 highcharts 中使用它,例如:

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

我重构了您的示例以展示方法:http://jsfiddle.net/wo7zn0bw/

关于javascript - 使用 JSON 将格式化 JavaScript 代码传递给 HighCharts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26472001/

相关文章:

JavaScript 堆栈,LIFO 堆栈 : value not as expected

javascript - jquery同步ajax仅在循环结束时附加到html

javascript - jQuery.ajax() - 如何最好地处理超时?

javascript - 为什么 JSON 不支持 NaN 时 MongoDB 允许 NaN 值?

javascript - 如何查找 href 值包含两个给定字符串的 <a> 元素

javascript - 为什么 dojo CDN 导入代码中不存在该协议(protocol)

javascript - FB 是未定义的,即使我刚刚使用它

javascript - 如何在ajax中使用jquery get方法动态更改html

java - 使用 JSONpath 验证根节点数组是否存在

javascript - C# 相当于序列化 json