解析包含带函数的序列化对象的HTTP响应

时间:2016-12-05 20:01:21

标签: javascript jquery json ajax highcharts

我有一个简单的javascript / jquery代码,它从某些Web服务请求数据,该数据返回可用于创建highcharts条形图的数据。来自服务器的响应无法解析为JSON,因为它包含一个单击事件处理程序,该处理程序无法由JSON.parse解析,错误为Unexpected keyword ....

javascript代码如下所示

$.ajax({
    type:"POST",
    url:"service/call"
}).done(function( xdata ) {
  // this is not going to work as xdata is not object but plain text
  $('#container').highcharts(xdata);
});

来自服务器的响应就像

{
 "chart" : {
   "type" : "bar"
 },
 "series" : [ {
   "data" : [ 25, 10 ]
 } ],
 "title" : {
   "text" : ""
 },
 "xAxis" : [ {
   "categories" : [ "data1", "data2"],
  "allowDecimals" : false
 } ],
 "yAxis" : [ {
   "title" : {
     "align" : "high",
     "text" : "Some Title"
   },
   "allowDecimals" : false,
   "labels" : {
     "overflow" : "justify"
   },
   "min" : 0
 } ],
 "credits" : {
   "enabled" : false
 },
 "plotOptions" : {
   "bar" : {
     "colors" : [ "#87bdee", "#ffcccc"],
     "colorByPoint" : true,
     "dataLabels" : {
       "enabled" : true
     },
  "point" : {
       "events" : {
         "click" : function(){window.location.href = '/data?type=' + (this.x == 0 ? 'data1' : (this.x == 1 ? 'hold' : (this.x == 2 ? 'data2' : (this.x == 3 ? 'data3' : (this.x == 4 ? 'data4' : (this.x == 5 ? 'data5' : (this.x == 6 ? 'data6' : 'data7')))))) )}
       }
     }
   }
 },
 "tooltip" : {
   "valueSuffix" : " elements"
 },
 "creditOptions" : {
   "enabled" : false
 }
}

我可以访问服务器端和客户端代码。

那么有一种简单的方法可以让事情发挥作用吗?我的意思是如何在不改变响应的情况下创建高图?

2 个答案:

答案 0 :(得分:2)

这就是我过去所做的。

<script type="text/javascript">

   function highChartOnClick() {
       alert('the click worked');
       window.location.href = '/data?type=' + (this.x == 0 ? 'data1' : (this.x == 1 ? 'hold' : (this.x == 2 ? 'data2' : (this.x == 3 ? 'data3' : (this.x == 4 ? 'data4' : (this.x == 5 ? 'data5' : (this.x == 6 ? 'data6' : 'data7')))))) );
   }

    $.ajax({
        type:"POST",
        url:"service/call"
    }).done(function( xdata ) {
         var someConfigurationJSONObject = xdata;
        someConfigurationJSONObject['plotOptions']['bar']['point']['events']['click'] = highChartOnClick;

         $('#container').highcharts(someConfigurationJSONObject);
    });
</script>

答案 1 :(得分:2)

  

如果使用 JSON.stringify with a "replacer" function ,您确实可以将存储/传递的函数转换为可调用代码   JSON.parse with a "reviver" function以及new Function()

有关完整的工作示例,请参阅 this previous post of mine

相关问题