我有一个jquery图表,我有这样的数据点:
var chart = new CanvasJS.Chart("chartContainer",
{
title: {
text: "MONTHLY STATISTICS"
},
axisX: {
title: "Axis X Title"
},
axisY: {
title: "Total Number"
},
data: [
{
type: "column",
dataPoints: [
{ x: 10, y: 6, label:"Apple"},
{ x: 20, y: 2, label:"Mango"},
{ x: 30, y: 5, label:"Orange"},
{ x: 40, y: 7, label:"Banana"},
{ x: 50, y: 1, label:"PineApple"},
{ x: 60, y: 5, label:"Pears"},
{ x: 70, y: 5, label:"Grapes"},
{ x: 80, y: 2, label:"Lychee"},
{ x: 80, y: 2, label:"Jackfruit"}
]
}
]
});
chart.render();
我有一个网络服务,我获取json格式数据,我将其存储在图表数据点格式的字符串变量s中。用于从Web服务接收数据并将其转换为图表数据点格式的代码如下:
success: function(datas)
{
var points = datas.d;
var s = "";
$.each(points, function (index, Info) {
s = s + "{x:" + Info.x + ", y:" + Info.y + ", label:\"" + Info.label + "\"},";
});
现在我遇到的问题是,当我将字符串's'作为数据点值时,它不起作用。 我的完整代码是这样的:
<script type="text/javascript">
$(document).ready(function () {
var dataSent = "{roll:" + 1 + ",name:\"" + "Mubashir\"}";
$.ajax({
type: "Post",
url: "WebServices.aspx/LoadStatistics",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(datas)
{
var points = datas.d;
var s = "";
$.each(points, function (index, Info) {
s = s + "{x:" + Info.x + ", y:" + Info.y + ", label:\"" + Info.label + "\"},";
});
var chart = new CanvasJS.Chart("chartContainer",
{
title: {
text: "MONTHLY STATISTICS"
},
axisX: {
title: "Axis X Title"
},
axisY: {
title: "Total Number"
},
data: [
{
type: "column",
dataPoints: [
s
]
}
]
});
chart.render();
}
,
failure: function (msg) {
alert(msg.d);
$("#LoginRecords").text('No information Available!');
}
});
});
</script>
<script src="tabs/js/canvasjs.min.js"></script>
如果我删除s变量并插入虚拟数据点,它可以正常工作。现在我的问题是如何使用来自Web服务的数据作为图表数据点。
答案 0 :(得分:1)
您尝试从服务器响应中创建一个字符串。要迭代服务器响应,您需要解析JSON。
尝试这样的事情:
var yourDataPoints = [];
$.each(points, function (index, Info) {
yourDataPoints.push({
x: Info.x,
y: Info.y,
label: Info.label
});
});
稍后分配您的yourDataPoints
数组。
data: [
{
type: 'column',
dataPoints: yourDataPoints
}
]
答案 1 :(得分:0)
试试这个: “dataPoints:jQuery.parseJSON(s)”
dataPoints期望的json对象数组和你的代码“s”是字符串,所以请先转换成Json对象然后才能工作