我在处理Highchart时遇到了一个奇怪的错误。
它可以很好地处理静态数据,但在从服务器端进行操作时真的很烦人。
我正在使用的代码,
function GetTab1() {
debugger;
$('#dvException').html('');
$('#dvException').invisible();
debugger;
var apiUrl = '../api/Home/GetTab?dumy1=1';
$.ajax({
url: apiUrl,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
if (data.length > 0) {
var Mychartdata = $.parseJSON(data);
var chartdata = [['Firefox', 45], ['IE', 26], ['Safari', 8], ['Opera', 6], ['Others', 0]];
// Radialize the colors
Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function (color) {
return {
radialGradient: { cx: 0.5, cy: 0.3, r: 0.7 },
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
]
};
});
// Build the chart
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'My Title'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.point.y;
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: Mychartdata
}]
});
};
[HttpGet]
public string GetTab(int dumy1)
{
string str = string.Empty;
DataTable dt = new DataTable();
dt = GetDataTableForPieChart();
str = GetJson(dt);
return str;
}
private DataTable GetDataTableForPieChart()
{
DataTable nt = new DataTable("new table");
nt.Columns.Add("key");
nt.Columns.Add("Value", typeof(int));
nt.Rows.Add("Firefox", 45.0);
nt.Rows.Add("IE", 26.8);
nt.Rows.Add("Safari", 8.5);
nt.Rows.Add("Opera", 6.2);
nt.Rows.Add("Others", 0.7);
return nt;
}
public string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows =
new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName.Trim(), dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
真的很困惑?一切都工作得很好,甚至从服务器获取正确格式的数据,但图表没有创建...但同样的做法与静态数据一样好..
答案 0 :(得分:0)
我刚刚更改了GetJson方法。以前它没有正确序列化。需要为它排除列名。
public string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
List<object[]> obj = new List<object[]>();
foreach (DataRow dr in dt.Rows)
{
obj.Add(dr.ItemArray);
}
return serializer.Serialize(obj);
}