谷歌图表json数据未加载

本文关键字:加载 数据 json 谷歌 | 更新日期: 2023-09-27 17:51:15

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

这是我的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)'/"}]"

关于为什么数据不加载有什么想法吗?

谷歌图表json数据未加载

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++)

此外,由于数据参数支持日期类型,您可以考虑将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>

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

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