我正在使用谷歌图表,并希望在Google Chart中动态添加行和列。我尝试使用下面的ajax,但它不起作用。
此处NumCols
未定义且在添加行时出错
未捕获错误:如果为addRow赋予参数,则它必须是数组,或者为null
Ajax的: -
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/home/DrawChart',
data: '{}',
success: function (chartsdataSet) {
data = new google.visualization.DataTable();
var chartsdata = JSON.parse(chartsdataSet).Table;
var numRows = chartsdata.length;
var numCols = chartsdata[0].length;
data.addColumn('string', chartsdata[0][0]);
// all other columns are of type 'number'.
for (var i = 1; i < numCols; i++)
data.addColumn('number', chartsdata[0][i]);
// now add the rows.
for (var j = 1; j < numRows; j++)
data.addRow(chartsdata[j]);
chart = new google.visualization.Table(document.getElementById('Graph1'));
chart.draw(data, options);
});
解析后的JSON对象: -
答案 0 :(得分:0)
使用以下循环,我得到动态行和列。
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/home/DrawChart',
data: '{}',
success: function (chartsdataSet) {
data1 = new google.visualization.DataTable();
var chartsdata1 = JSON.parse(chartsdataSet).Table;
var myVal = [];
var colName;
var colCount = 0;
for (var i = 0; i < chartsdata1.length; i++) {
var row = chartsdata1[i];
myVal.length = 0;
$.each(row, function (key, value) {
if (i == 0) {
if (colCount == 0) {
colName = key;
data1.addColumn('string', colName);
colCount += 1;
}
else {
data1.addColumn('number', key);
}
}
myVal.push(value);
}); data1.addRow(myVal);
}
});