我一直在尝试创建Google图表。如果我在DrawChart Function中对值进行硬编码,则它会起作用,但是当我从aspx.cs页传递值时,它不起作用,它只会显示空白页。 我不知道我在哪里犯错。 下面是HTML和C#代码
HTML页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Chart2.aspx.cs" Inherits="CarriageReturn.Chart2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
$.ajax({
type: "POST",
url: "Chart2.aspx/GetChartData()",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var chartdata = new google.visualization.DataTable();
chartdata.addColumn('string', 'Topping');
chartdata.addColumn('number', 'Slices');
chartdata.addRows(r.d);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(chartdata, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="chart_div"></div>
</div>
</form>
</body>
</html>
C#页面:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CarriageReturn
{
public partial class Chart2 : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
GetChartData();
}
[WebMethod]
public static List<object> GetChartData()
{
List<object> chartData = new List<object>();
chartData.Add(new object[] { "Mushrooms", 3 });
chartData.Add(new object[] { "Onions", 1 });
chartData.Add(new object[] { "Olives", 1 });
chartData.Add(new object[] { "Zucchini", 1 });
chartData.Add(new object[] { "Pepperoni", 1 });
return chartData;
}
}
}
我需要将值从数据库传递到图表。