我正在尝试使用 JQuery Flot Charts http://www.flotcharts.org/在我的 MVC 5 应用程序中。目前我只是想了解它们是如何工作的。我使用了创建条形图的示例代码:
$(document).ready(function () {
$(function () {
var data = [[0, 5],[1, 10],[2, 15],[3, 20],[4, 25],[5, 30]];
var dataset = [{ label: "2012 Average Temperature", data: data, color: "#5482FF" }];
var ticks = [[0, "London"], [1, "New York"], [2, "New Delhi"], [3, "Taipei"],[4, "Beijing"], [5, "Sydney"]];
var options = {
series: {
bars: {
show: true
}
},
bars: {
align: "center",
barWidth: 0.5
},
xaxis: {
axisLabel: "World Cities",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10,
ticks: ticks
},
legend: {
noColumns: 0,
labelBoxBorderColor: "#000000",
position: "nw"
},
grid: {
hoverable: true,
borderWidth: 2,
backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
}
};
$.plot($("#placeholder"), dataset, options);
});
});
如果我要使用 JQuery Flot Charts,我需要能够通过 AJAX 动态提取数据,而不是像上面那样硬编码到我的 Razor View 中。
我在 Controller 中创建了一个操作,它返回与硬编码到上面示例中的数据相同的数据
[HttpGet]
public ActionResult GetTestData()
{
return Json(new[] { new[] { 0, 5 }, new[] { 1, 10 }, new[] { 2, 15 }, new[] { 3, 20 }, new[] { 4, 25 }, new[] { 5, 30 }, new[] { 6, 35 } },JsonRequestBehavior.AllowGet);
}
然后,我通过注释掉数据和绘图调用来修改 Razor View 中的代码,并将其替换为 Ajax 请求
//var data = [[0, 11],[1, 15],[2, 25],[3, 24],[4, 13],[5, 18]];
//$.plot($("#placeholder"), dataset, options);
$.ajax({
type: "GET",
url: '@Url.Action("GetTestData")',
error: function () {
alert("An error occurred.");
},
success: function (data) {
$.plot($("#placeholder"), dataset, options);
}
});
此 Ajax 请求随后应调用我的 Controller 中的 GetTestData 操作并返回 Json 数据。但是,我在 GetTestData 操作上放置了一个断点,进行了调试,并且该操作永远不会被调用,因此永远不会返回数据来创建条形图。
谁能帮我找出为什么我的 Ajax 代码没有调用我的 Action。
感谢您的任何反馈。
最佳答案
各位,问题出在这行代码
var dataset = [{ label: "2012 Average Temperature", data: data, color: "#5482FF" }];
不在我的 Ajax 调用范围内。这意味着在这行代码中,变量 data
已被赋值,但它并不存在。
因此,解决方案是将浮点图特定代码移至 Ajax 调用的成功函数内,如下所示
$.ajax({
type: "GET",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/Statistics/GetTestData/',
error: function () {
alert("An error occurred.");
},
success: function (data) {
//alert("Success.");
var dataset = [{ label: "2012 Average Temperature", data: data, color: "#5482FF" }];
var ticks = [[0, "London"], [1, "New York"], [2, "New Delhi"], [3, "Taipei"], [4, "Beijing"], [5, "Sydney"]];
var options = {
series: {
bars: {
show: true
}
},
bars: {
align: "center",
barWidth: 0.5
},
xaxis: {
axisLabel: "World Cities",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10,
ticks: ticks
},
legend: {
noColumns: 0,
labelBoxBorderColor: "#000000",
position: "nw"
},
grid: {
hoverable: true,
borderWidth: 2,
backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
}
};
$.plot($("#placeholder"), dataset, options);
}
});
希望这对其他人有帮助。
关于jquery - 使用 Ajax 和 Json 填充 JQuery Flot 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26214558/