代码之家  ›  专栏  ›  技术社区  ›  Tracy Zhou

如何将JSON转换为谷歌图表数据?

  •  1
  • Tracy Zhou  · 技术社区  · 6 年前

    我有一个函数,它在MVC Web应用程序的控制器中返回JSON。

    public ActionResult GetWeeklyStats()
    {
         using (DBContext db = new DBContext())
         {
              var result = db.sp_StoredProcedureName.ToList();
              return Json(result, JsonRequestBehavior.AllowGet);
         }
    }
    

    返回的数据如下:

       [
           {
              "WeekNo" : 1,
              "Count" : 230
           },
           {
              "WeekNo" : 2,
              "Count" : 240
           },
           {
              "WeekNo" : 3,
              "Count" : 250
           },
           {
              "WeekNo" : 4,
              "Count" : 260
           }
      ];
    

    我正试图在我的视图中设置我的谷歌图表数据。以下是我的视图中的Ajax调用:

     $.ajax({
            type: "GET",
            dataType: 'json',
            contentType: 'application/json',
            url: '@Url.Action("GetWeeklyStats", "myControllerName")',
            async: false,
            success: function (data) {
                //set google data here ......
                //how to do it here???
            }
        });
    

    谷歌数据应该如下所示:

    // Create the data table.
    var gcData = new google.visualization.DataTable();
    gcData.addColumn('number', 'WeekNo');
    gcData.addColumn('number', 'Count');
    gcData.addRows([
        [1, 230],
        [2, 240],
        [3, 250], 
        [4, 260]
    ]);
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   WhiteHat    6 年前

    使用可以使用 addRow 方法添加数据中每个对象的值

    请参阅以下代码段…

    $.ajax({
        type: "GET",
        dataType: 'json',
        contentType: 'application/json',
        url: '@Url.Action("GetWeeklyStats", "myControllerName")',
        async: false,
        success: function (data) {
            // Create the data table.
            var gcData = new google.visualization.DataTable();
            gcData.addColumn('number', 'WeekNo');
            gcData.addColumn('number', 'Count');
    
            $.each(data, function(i, row) {
                gcData.addRow([
                    row.WeekNo,
                    row.Count
                ]);
            });
        }
    });