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

标签 javascript jquery json ajax highcharts

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

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
 }
}

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

那么有没有一种简单的方法可以让事情顺利进行呢?我的意思是如何在不更改响应的情况下创建 Highcharts ?

最佳答案

You can indeed turn a function stored/passed as a string into callable code if you use JSON.stringify with a "replacer" function and JSON.parse with a "reviver" function along with new Function()

参见this previous post of mine 完整的工作示例。

关于javascript - 解析包含带函数的序列化对象的 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40982360/

相关文章:

javascript - 在 Vue.js 的 watch 中使用 try catch

javascript - 拖动并插入 div 到另一个 div

javascript - 单击后从 showcomments 中删除类() - 来自所有类似的类?

javascript - 使用 Meteor 防止表单提交

java - eBay Order API 在沙盒环境中抛出错误

c# - 如何在 C# Web 应用程序中为 FullCalendar 创建 JSON 提要

javascript - JavaScript 中的正则表达式

javascript - 如何在可以最小化的网站导航栏顶部创建报价条?

javascript - 运行 ChartEditor 后,setOptions() 不适用于 ChartWrapper 中的图表

javascript - Google map 标记未出现在 $.getJSON Javascript 中