我有一个简单的 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 andJSON.parse
with a "reviver" function along withnew Function()
参见this previous post of mine 完整的工作示例。
关于javascript - 解析包含带函数的序列化对象的 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40982360/