问题描述
我试图将从数据库中检索到的数据放入ajax调用成功的一部分中,这里有一个绘制Flot图表的功能。 从服务器返回的数据如下所示:
[[5,29],[6,57],[7,31]]
我想在Flot Chart“数据:”部分中使用它,它应该只是多维数组。 当我对值进行硬编码时,一切都很好,但是一旦我使用了来自Ajax的响应,它将无法工作。 我已经使用$ .parseJSON(data.d)将其转换为我认为是正确的格式,并且当我写到javascript控制台时,它将显示为数组。 而且我可以注销数组的值,但是由于未知的原因,它不会绘制图表。
这是代码(数据:obj)运行不正常:
function chart2() {
if ($('#chart_2').size() != 1) {
return;
}
var selless = {};
selless.LessonID = '5';
selless.UserID = '8';
$.ajax({
url: "Default.aspx/GetChartData",
type: 'POST',
data: '{selless: ' + JSON.stringify(selless) + '}',
contentType: "application/json; charset=utf-8",
success: function (data) {
var obj = $.parseJSON(data.d)
console.log(obj[1]);
var options = {
series: {
lines: {
show: true,
lineWidth: 2,
fill: true,
fillColor: {
colors: [{
opacity: 0.05
}, {
opacity: 0.01
}]
}
},
points: {
show: true,
radius: 3,
lineWidth: 1
},
shadowSize: 2
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#eee",
borderColor: "#eee",
borderWidth: 1
},
colors: ["#d12610", "#37b7f3", "#52e136"],
xaxis: {
ticks: 11,
tickDecimals: 0,
tickColor: "#eee",
},
yaxis: {
ticks: 11,
tickDecimals: 0,
tickColor: "#eee",
}
}
var visitors = [
[5, 29], [6, 57], [7, 31]
];
var data = [{
data: obj,
label: "Unique Visits",
lines: {
lineWidth: 1,
},
shadowSize: 0
}, {
data: visitors,
label: "Page Views",
lines: {
lineWidth: 1,
},
shadowSize: 0
}];
$.plot("#chart_2", data, options);
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 15,
border: '1px solid #333',
padding: '4px',
color: '#fff',
'border-radius': '3px',
'background-color': '#333',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#chart_2").bind("plothover", function(event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y);
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
}``
1楼
var obj = $ .parseJSON(data.d); 上面的代码段在解析json之前访问数组元素。
相反,首先解析json,然后访问值。 将成功功能的前两行更改为:
var obj = $ .parseJSON(data); console.log(obj.d);