[英]Ajax call response to array apply to data section of flot chart
我試圖將從數據庫中檢索到的數據放入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;
}
});
}``
var obj = $ .parseJSON(data.d); 上面的代碼段在解析json之前訪問數組元素。
相反,首先解析json,然后訪問值。 將成功功能的前兩行更改為:
var obj = $ .parseJSON(data); console.log(obj.d);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.