Google 图表 json 数据未加载

Google Charts json data not loading

我正在使用 ASP.NET MVC 和 Google 图表来尝试生成一个包含两个数据记录的简单折线图。我成功地从数据库中提取数据,但数据没有出现在我的图表上。数据由两个记录和两个字段组成:WeekOfEntry(DateTime) 和 Weight(十进制)。图表出现,但数据点不存在。我猜我的数据格式不正确?

这是我的 javascript:

<script type="text/javascript">

    //Load the Visualization API library and the linechart library.
    google.load('visualization', '1.0', { 'packages': ['corechart'] });

    //Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawLoseATonLineChart);

    //Callback that creates and populates a data table, instantiates the line chart,
    //passes in the data, and draws it.
    function drawLoseATonLineChart() {

        var url = "@Url.Action("GetChartStatistics")";

        var jsonData = $.ajax({
            method: 'GET',
            url: url,
            dataType: 'JSON',
            async: false
        }).responseText;

        var data = new google.visualization.DataTable();
        data.addColumn('string', 'WeekOfEntry');
        data.addColumn('number', 'Weight');

        for (var i = 0; i < data.length; i++) {
            data.addRow([jsonData[i].WeekOfEntry, jsonData[i].Weight]);
        }

        var options = {
            title: 'Weight Progression',
            legend: {
                position: 'right',
                alignment: 'center'
            },
            vAxis: {
                title: 'Weight'
            },
            hAxis: {
                title: 'Week',
                slantedText: true,
                slantedTextAngle: 45

            },
            colors: ['E81A00']
        };

        var chart = new google.visualization.LineChart(document.getElementById('lose-a-ton-line-chart'));

        chart.draw(data, options);
    }
</script>

这是我的 GetChartStatistics() 方法的一部分:

var lineChartData = (from a in db.Associates
            join aw in db.AssociateWeights
                on a.RegistrationId equals aw.RegistrationId
            where a.EventId == eventId &&
                  a.Username == currentuser
            select new LineChartData
            {
                Weight = aw.Weight,
                WeekOfEntry = aw.WeekOfEntry
            });

return Json(lineChartData, JsonRequestBehavior.AllowGet);

编辑:这是我的 JSON 数据返回时的格式化方式:

"[{"Weight":190.0,"WeekOfEntry":"\/Date(1431921600000)\/"},{"Weight":121.0,"WeekOfEntry":"\/Date(1432526400000)\/"}]"

关于数据为何未加载的任何想法?

您是否尝试过 arrayToDataTable 函数,而不是遍历 JSON 数据?

var dataTableData = google.visualization.arrayToDataTable(JSON.parse(jsonData));

你的 for 循环有问题。这是您修改后的代码。

//Load the Visualization API library and the linechart library.
    google.load('visualization', '1.0', { 'packages': ['corechart'] });

    //Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawLoseATonLineChart);

var url = "@Url.Action("GetChartStatistics")";

var result = $.ajax({
    method: 'GET',
    url: url,
    dataType: 'JSON',
    async: false
});
var jsonData = result.responseText;
var data = new google.visualization.DataTable();
data.addColumn('string', 'WeekOfEntry');
data.addColumn('number', 'Weight');

$.each(JSON.parse(jsonData), function (index, obj) {
    data.addRow([obj.WeekOfEntry, obj.Weight]);
});

var options = {
    title: 'Weight Progression',
    legend: {
        position: 'right',
        alignment: 'center'
    },
    vAxis: {
        title: 'Weight'
    },
    hAxis: {
        title: 'Week',
        slantedText: true,
        slantedTextAngle: 45

    },
    colors: ['E81A00']
};

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

chart.draw(data, options);


public JsonResult GetChartStatistics()
    {
        var lineChartData = new List<LineChartData>() { 
            new LineChartData() { WeekOfEntry = "sat", Weight = 1},
            new LineChartData() { WeekOfEntry = "sat1", Weight = 2},
            new LineChartData() { WeekOfEntry = "sat2", Weight = 3},
            new LineChartData() { WeekOfEntry = "sat3", Weight = 4},
        };

        return Json(lineChartData, JsonRequestBehavior.AllowGet);
    }

您的示例中有一个拼写错误,您可能想要迭代 jsonData 对象,因此将行替换为:

for (var i = 0; i < data.length; i++) {

for (var i = 0; i < jsonData.length; i++)

此外,由于 data parameter supports date type,您可以考虑将 Week 呈现为日期而不是 Json 字符串。

例子

google.setOnLoadCallback(drawLoseATonLineChart);

function drawLoseATonLineChart() {

    var jsonData = [
        { "Weight": 190.0, "WeekOfEntry": "\/Date(1431921600000)\/" },
        { "Weight": 121.0, "WeekOfEntry": "\/Date(1432526400000)\/" }
    ];


    var data = new google.visualization.DataTable();
    data.addColumn('date', 'WeekOfEntry');
    data.addColumn('number', 'Weight');

    for (var i = 0; i < jsonData.length; i++) {
        var weekOfEntry = new Date(parseInt(jsonData[i].WeekOfEntry.substr(6,13)));
        data.addRow([weekOfEntry, jsonData[i].Weight]);
    }

    var options = {
        title: 'Weight Progression',
        legend: {
            position: 'right',
            alignment: 'center'
        },
        vAxis: {
            title: 'Weight'
        },
        hAxis: {
            title: 'Week',
            slantedText: true,
            slantedTextAngle: 45

        },
        colors: ['E81A00']
    };

    var chart = new google.visualization.LineChart(document.getElementById('lose-a-ton-line-chart'));
    chart.draw(data, options);
}
 <script type="text/javascript" src="https://www.google.com/jsapi?autoload={ 'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<div id="lose-a-ton-line-chart" style="width: 640px; height: 480px"></div>