有一个JavaScript问题,AJAX代码显示数据

时间:2016-06-10 18:01:28

标签: javascript jquery json ajax highcharts

我需要你的一些提示来解决我在JavaScript,AJAX和JSON数据方面遇到的问题。我想在我的网页上填写带有条形图的通用集(我正在使用HighCharts)。数据采用JSON格式,从一开始我只使用日期和值作为对数据集。解决方案很好,我只有一个条形图,但我的页面上有很多图表,我需要显示所有这些(最多12个)。

现在我想调整显示多个图表。在下面的代码中,DataMacro数组可以正常使用图表。它还有一个匹配a的硬编码ID。现在我在页面中有一系列像id = barchart11,id = barchar21,依此类推。在数据集中,我创建了一个名为PanelCodeUI的标签,我将使用循环遍历数据集。问题是如何做到这一点。每个循环现在将填写所有船只的所有日期和价值。

此外,我需要重新构建显示条形图的功能。最好的方法是调用一个带有数据数组和panelCodeUI id的函数,只需替换条形图的名称并按原样设置在datamacro中。但我不知道该怎么做。数据在所有容器之间混合,我需要在发送到函数之前收集所有数据。因此AJAX和JavaScript的问题是异步的。我需要确保它的行为正确而快速。

也许我需要更改我的数据集,或者我需要在几个步骤中执行此操作,例如查找所有容器ID然后执行另一个AJAX调用以从容器中获取日期,值对然后显示。我希望有一种方法可以用这个数据集做到这一点,并希望有人可以帮助我这个

这里有一些JSON数据集:

[
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":844,"VesselId":1,"SectorId":2,"PanelCodeUI":"21","VesselCodeUI":"21","VesselSorting":1},

{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":8720,"VesselId":4,"SectorId":1,"PanelCodeUI":"11","VesselCodeUI":"12","VesselSorting":2},

{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":948,"VesselId":5,"SectorId":1,"PanelCodeUI":"11","VesselCodeUI":"11","VesselSorting":1},

{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":0,"VesselId":6,"SectorId":3,"PanelCodeUI":"31","VesselCodeUI":"31","VesselSorting":1},

{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465171200000,"Value":2067,"VesselId":1,"SectorId":2,"PanelCodeUI":"21","VesselCodeUI":"21","VesselSorting":1}
]

到目前为止,这是JavaScript代码:

$(function () {
            var datamacro = [];
            $.ajax({
                type: "POST",
                url: '../Services/HighChartService.asmx/GetOilProductionLast5DaysByActiveVessels',
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (seriedata) {
                    console.log(JSON.stringify(seriedata.d));
                    var productions = seriedata.d;

                    $.each(productions, function (index, productions) {
                        var yval = productions.Value;
                        var xval = productions.Date;
                        var x = [xval, yval];
                        datamacro.push(x);

                        //alert("productions Name: " + productions.Date + "\nID: " + productions.Value);
                    });

                    $(function () {
                        //var bchart = '#barchart' + vesselindex.toString();

                        // want this to be looped with generic names like #barchart11, #barchart21, #barchart31 and so on
                        $('#barchart11').highcharts({
                            chart: {
                                type: 'column'
                            },
                            title: {
                                text: 'LAST FIVE DAYS'
                            },
                            subtitle: {
                                text: ''
                            },
                            xAxis: {
                                type: "datetime",
                                tickInterval: 24 * 3600 * 1000,
                                labels: {
                                    rotation: -45,
                                    align: 'right'
                                },
                                dateTimeLabelFormats: { // don't display the dummy year
                                    day: '%e. %b',
                                },
                                //crosshair: true
                            },
                            credits: {
                                enabled: false
                            },
                            yAxis: {
                                labels: {
                                    enabled: false
                                },
                                title: {
                                    text: null
                                }

                            },
                            tooltip: {
                                formatter: function () {
                                    return Highcharts.dateFormat('%d/%m/%Y', new Date(this.x)) + '<br/>' + ' in barrels: ' + this.y;
                                }
                            },
                            plotOptions: {
                                column: {
                                    pointPadding: 0.2,
                                    borderWidth: 0
                                }, series: {
                                    pointRange: 24 * 3600 * 1000, // one day
                                    pointInterval: 3600 * 1000
                                }
                            },
                            series: [{
                                //name: '',
                                showInLegend: false,
                                data: datamacro,
                                dataLabels: {
                                    enabled: true,
                                    rotation: -90,
                                    color: '#FFFFFF',
                                    align: 'right',
                                    format: '{point.y:.1f}', // one decimal
                                    y: 10, // 10 pixels down from the top
                                    style: {
                                        fontSize: '13px',
                                        fontFamily: 'Verdana, sans-serif'
                                    }
                                }
                            }]
                        });
                    });
                },
                error: function (r) {
                    alert(r.responseText);
                },
                failure: function (r) {
                    alert(r.responseText);
                }
            });
        });

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你想为每个不同的panelCodeUI绘制一个图表?

如果是这种情况,请在AJAX成功后用以下代码更改代码:

var productions = seriedata.d;

var listPanelCodeUI = productions.map(function(p){return p.PanelCodeUI}).filter(function(item, pos, self) {
    return self.indexOf(item) == pos;
});
//listPanelCodeUI : [21,11,31]

listPanelCodeUI.sort();

listPanelCodeUI.forEach(function(e){

   datamacro = [];

   //Create a div for each panelCodeUI
   $("body").append("<div id='barchart" + e + "'></div>");

   var divId = "#barchart"+e;

   //Filter productions for specific panelCodeUI
   var data = productions.filter(function(p){return p.panelCodeUI === e});

   data.forEach(function(d){
      var yval = d.Value;
      var xval = d.Date;
      var x = [xval, yval];
      datamacro.push(x);
   });

  $(function () {
      $(divId).highcharts({

      ...

      })
   })
}

答案 1 :(得分:1)

这就是解析数据所需的内容:

charts = [];
$.each(productions.map(function(el) {
    return el.PanelCodeUI;
  }).filter(function(el, index, arr) {
    return arr.indexOf(el) === index;
  }), function(index,PanelCodeUI) {
    var serie = productions.filter(function(el) {
      return el.PanelCodeUI === PanelCodeUI;
    });
    $.each(serie, function(index, production) {
      datamacro.push([production.Value, production.Date]);
    });
    drawChart('#barchart' + PanelCodeUI, 'LAST FIVE DAYS', datamacro);
  });

我还创建了这个辅助函数来创建图表:

function drawChart(containerID, chartTitle, data) {
  charts.push(new Highchart.Chart({
    chart: {
      type: 'column',
      renderTo: containerID
    },
    title: {
      text: chartTitle
    },
    subtitle: {
      text: ''
    },
    xAxis: {
      type: "datetime",
      tickInterval: 24 * 3600 * 1000,
      labels: {
        rotation: -45,
        align: 'right'
      },
      dateTimeLabelFormats: { // don't display the dummy year
        day: '%e. %b',
      },
      //crosshair: true
    },
    credits: {
      enabled: false
    },
    yAxis: {
      labels: {
        enabled: false
      },
      title: {
        text: null
      }

    },
    tooltip: {
      formatter: function() {
        return Highcharts.dateFormat('%d/%m/%Y', new Date(this.x)) + '<br/>' + ' in barrels: ' + this.y;
      }
    },
    plotOptions: {
      column: {
        pointPadding: 0.2,
        borderWidth: 0
      },
      series: {
        pointRange: 24 * 3600 * 1000, // one day
        pointInterval: 3600 * 1000
      }
    },
    series: [{
      //name: '',
      showInLegend: false,
      data: data,
      dataLabels: {
        enabled: true,
        rotation: -90,
        color: '#FFFFFF',
        align: 'right',
        format: '{point.y:.1f}', // one decimal
        y: 10, // 10 pixels down from the top
        style: {
          fontSize: '13px',
          fontFamily: 'Verdana, sans-serif'
        }
      }
    }]
  }));
}