如何使这段代码更简单或更短?

时间:2017-01-30 02:11:38

标签: javascript jquery highcharts

我有以下代码用于显示图表。我的问题是labelsdatasets是静态的而不是动态的。这有可能使dyanmic?。

var globalNewData = "";
function ChartDataLabel() {
    var barChartData = {
        labels: [globalNewData[0]["CandidateName"], globalNewData[1]["CandidateName"],
        globalNewData[2]["CandidateName"], globalNewData[3]["CandidateName"],
        globalNewData[4]["CandidateName"]],
        datasets: [{
            fillColor: "rgba(0,100,0,1)",
            strokeColor: "black",
            data: [globalNewData[0]["Votes"], globalNewData[1]["Votes"], globalNewData[2]["Votes"],
            globalNewData[3]["Votes"], globalNewData[4]["Votes"]] // Votes = Number of Votes
        }]
    }
    //var index = 11;
    var ctx = document.getElementById("canvas").getContext("2d");
    var barChartDemo = new Chart(ctx).Bar(barChartData, {
        responsive: true,
        barValueSpacing: 2
    });
}

NewData();
function NewData() {
    var url = '../Controller/_NewData'
    var res = "";
    $.ajax({
        type: "POST",
        url: url,
        dataType: 'json',
        // async: false,
        success: function (response) {
            var Data = response.data;
            globalNewData = Data;
            ChartDataLabel();

        },
        error: function (response) {
            alert("error");
            alert(response);
        }
    });
}

控制器

public JsonResult _NewData()
    {
        var Data = new List<object>();
        Data = (from a in db.Testings
                select new
                {
                    TestID = a.TestID,
                    CandidateName = a.Candidatename,
                    Position = a.Position,
                    Votes = a.NoOfVotes
                }).ToList<object>();

        return Json(new
       {
           data = Data
       }, JsonRequestBehavior.AllowGet);
    }

我在静态中的含义正如您在图表代码[globalNewData[0]["CandidateName"]中所看到的那样,修复(5)将在图表中显示多少数据。在Dynamic中,即使添加新数据,它也会在[6]...内添加数组。

任何建议都将被接受。

1 个答案:

答案 0 :(得分:1)

您可以为标签和数据集数据映射新数组

类似的东西:

function ChartDataLabel(chartData) {
    var barChartData = {
        labels: chartData.labels,// reference to labels array created below
        datasets: [{
            fillColor: "rgba(0,100,0,1)",
            strokeColor: "black",
            data: chartData.points // reference to points array created below
        }]
    }
    //var index = 11;
    var ctx = document.getElementById("canvas").getContext("2d");
    var barChartDemo = new Chart(ctx).Bar(barChartData, {
        responsive: true,
        barValueSpacing: 2
    });
}


$.ajax({
        ...
        success: function (response) {

            // object with new arrays need to pass to charting function
            var chartData ={
               labels:[],
               points:[]
            }
            // loop through response data and add to each of labels and points arrays
            response.data.forEach(function(item){
                chartData.labels.push(item.CandidateName);
                chartData.points.push(item.Votes);
            })
            // pass chartData into function
            ChartDataLabel(chartData);
       }
  })

还有许多其他方法可用于映射这些新数组,这些方法还可以减少所需的代码。我使用了更长的方法来更好地理解

替代方法是在服务器上执行此映射并从服务器发送数据,以便response.data包含所需的标签和点数组