1

部分视图:

var dataa;
    $.ajax({
        url: ServerUrl + '/Dashboard/GetData',
        type: 'POST',
        cache: false,
        dataType: 'text',
        async: true,
        error: function (xhr) {
            //alert('Error: ' + xhr.statusText);
        },
        success: function (result) {
            debugger;
            dataa = result;
            var chart = c3.generate({
                data: {
                    type: 'bar',
                    json: [
                        dataa
                    ],
                    keys: {
                        x: 'indicator',
                        value: ['total']
                    }
                },
                axis: {
                    x: {
                        type: 'category'
                    }
                },
                bar: {
                    width: {
                        ratio: 0.5
                    }
                }
            });
        }
    });

控制器 Json 代码

public string GetData()
{
return "{ 'indicator': 'X', 'total': 100 },{ 'indicator': 'Y', 'total': 200 },{ 'indicator': 'Z', 'total': 300 }";
}

当我使用上面的代码时它不起作用,但是如果我按照这个 JS Fiddle链接中指定的方式传递 json 数据,它就会起作用。我是否从控制器错误地传递了 JSON 数据。?

请帮忙。

4

1 回答 1

4

您不会从方法 GetData 返回 JSON。这样做返回JSON

public JsonResult GetData()
   { 
       var data = new[] {
          new { indicator= "X", total = 100 },
          new { indicator= "Y", total = 200 },
          new { indicator= "Z", total = 300 }
       };

           return  Json(data,JsonRequestBehavior.AllowGet);
   }

并像这样进行ajax调用:

 $.ajax({
         cache: false,
         type: "GET",
         url:URL,
         dataType: 'json',
         success: function (result)
         {
           console.log(result);
         },
         error: function (xhr, ajaxOptions, thrownError)
         {
          alert('Failed to retrieve data.');                    
         }
       });
于 2015-03-18T06:07:25.447 回答