Javascript ajax get data undefined from C#

2019-07-28 21:33发布

I want to build a web page with google charts. I tried to build it with c# as a web form and get data from local database to javascript. But that's not working and i'm having data is undefined in the response of ajax. This is the code of c#

        [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static object[] GetChartData()
    {
        List<GoogleChartData> data = new List<GoogleChartData>();
        //Here MyDatabaseEntities  is our dbContext
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            data = dc.GoogleChartDatas.ToList();
        }
        var chartData = new object[data.Count + 1];
        chartData[0] = new object[]{
                "Product Category",
                "Revenue Amount"
            };
        int j = 0;
        foreach (var i in data)
        {
            j++;
            chartData[j] = new object[] { i.Product_Category, i.RevenueAmount };
        }return chartData;
    }

and the javascript code is:

        <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!-- Javascript Job-->
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
    var chartData; // globar variable for hold chart data
    google.load("visualization", "1", { packages: ["corechart"] });

    // Here We will fill chartData

    $(document).ready(function () {

        $.ajax({
            url: "GoogleChart.aspx/GetChartData",
            data: "",
            dataType: "json",
            type: "post",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                chartData = data.d;
                alert(chartData);
            },
            error: function () {
                alert("Error loading data! Please try again.");
            }
        }).done(function () {
            // after complete loading data
            google.setOnLoadCallback(drawChart);
            drawChart();
        });
    });


    function drawChart() {
        var data = google.visualization.arrayToDataTable(chartData);

        var options = {
            title: "Company Revenue",
            pointSize: 5
        };

        var pieChart = new google.visualization.PieChart(document.getElementById('chart_div'));
        pieChart.draw(data, options);

    }

</script>
<div id="chart" style="width: 500px; height: 400px">
</div>

Database is in picture

PLEASE HELP!! how to get my table data in ajax and put them in chart?

1条回答
混吃等死
2楼-- · 2019-07-28 21:43

first, recommend not using jsapi to load the library, according to release notes...

The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader (loader.js) from now on.

<script src="https://www.gstatic.com/charts/loader.js"></script>

this will only change the load statement...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

as seen above, the callback can be set in the load statement

the callback will let you know when google charts has loaded, along with the dom

thus no need for setOnLoadCallback or $(document).ready

as for the rest, recommend the following setup...

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!-- Javascript Job-->
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
    google.charts.load('current', {
      callback: drawChart,
      packages: ['corechart']
    });

    function drawChart() {
      $.ajax({
        url: "GoogleChart.aspx/GetChartData",
        data: "",
        dataType: "json",
        type: "post",
        contentType: "application/json; charset=utf-8",
      }).done(function (data) {
        var data = google.visualization.arrayToDataTable(data.d);
        var options = {
          title: "Company Revenue",
          pointSize: 5
        };
        var pieChart = new google.visualization.PieChart(document.getElementById('chart_div'));
        pieChart.draw(data, options);
      }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("Error: " + errorThrown);
      });
    }
</script>
<div id="chart" style="width: 500px; height: 400px">
</div>
查看更多
登录 后发表回答