使用ajax调用获取数据时,防止重绘高亮图

问题描述 投票:0回答:1

我想知道是否有人使用Highchart遇到了这个问题。我使用从API动态获取数据并将它们渲染到条形图。我想要做的是每次获取更新的数据时它都会呈现到条形图中。这是我到目前为止:

$(function() {
  window.campaign_graph_data = [];
  function getCampaigns() {
    dashboard_data = {
      user_id: window.userId
    };

    $.ajax({
      url: window.apiURL + "tally/api/tally/all",
      type: "POST",
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify(dashboard_data),
      headers: {
        Authorization: window.currentUser + " " + window.apiKey
      },
      dataType: "json",

      success: function(response) {
        console.log(response.data);
        var api_options;
        if (response.data.length != 0) {
          $(".no-data-dashboard").addClass("hide");
          $.each(response.data, function(key, value) {
            api_options =
              '<option id="campaign-' +
              value.id +
              '" value="' +
              value.id +
              '">' +
              value.tally_name +
              "</option>";
            $(".campaign-dropdown").append(api_options);
          });
          $(".campaign-dropdown option:nth-child(2)").val();
          $(".campaign-dropdown option:nth-child(2)").prop("selected", true);
          $(".campaign-dropdown").trigger("change");
          $("#dashboard-btn-graph").addClass("dashboard-button-active");
          $(".show-graph").removeClass("hide");
          $(".campaign-dropdown option:nth-child(1)").remove();
          $(".dashboard-btn").prop("disabled", false);
          $(".campaign-dropdown").prop("disabled", false);
        } else {
          $(".no-data-dashboard").removeClass("hide");
        }
      },
      error: function(response) {
        console.log(response);
      }
    });
  }

  getCampaigns();

  $(".select2-dropdown").select2();

  $(document).off("change", ".campaign-dropdown");
  $(document).unbind("change", ".campaign-dropdown");
  $(document).on("change", ".campaign-dropdown", function() {
    selected_campaign = $(this).val();
    getCampaignbyId(selected_campaign);

    window.poll_fetch = setInterval(function() {
      getCampaignbyId(selected_campaign);
    }, 10000);
  });

  function getCampaignbyId(id) {
    $.ajax({
      url: window.apiURL + "tally/api/dashboard/campaign/" + id,
      type: "GET",
      contentType: "application/json; charset=utf-8",
      headers: {
        Authorization: window.currentUser + " " + window.apiKey
      },
      dataType: "json",

      success: function(response) {
        console.log(response);
        campaign_graph_data = [];
        campaign_graph_legend_name = [];
        campaign_table_data = [];
        $.each(response, function(key, value) {
          var inc_value;
          if (value.increase != 0) {
            inc_value =
              '<span style="color:green">(' +
              " + " +
              value.increase +
              " increase )</span>";
          } else {
            inc_value = "";
          }

          response_graph_api_data = {
            name: value.Choice,
            data: [
              {
                y: parseInt(value.current),
                name: value.Choice,
                description: value.Description,
                color: value.option_color,
                increased_value: inc_value
              }
            ]
          };
          response_table_api_data = {
            name: value.Choice,
            color: value.option_color,
            current: value.current,
            increased_value: value.increase,
            percentage: value.percentage,
            previous: value.previous
          };
          campaign_graph_data.push(response_graph_api_data);
          campaign_table_data.push(response_table_api_data);
          campaign_graph_legend_name.push(value.Choice);
          localStorage.setItem(
            "Graph Data",
            JSON.stringify(campaign_graph_data)
          );
          //chart.redraw();
          //chart.series[].setData(campaign_graph_data,true)
        });
        console.log(campaign_graph_data);
        console.log(chart);
        //chart.series[0].name = campaign_graph_legend_name;

        /*if(campaign_graph_data.length == 2){
    					chart.setSize(null,200);
    				}

    				else if(campaign_graph_data.length <= 10){
    					chart.setSize(null,400);
    				}
    				else{
    					chart.setSize(null,500);
    				}*/
        console.log(campaign_graph_data.length);
        console.log(campaign_table_data);

        $(".chart-legend-items").empty();
        $(".table-graph-items-content").empty();

        $.each(campaign_graph_data, function(key, value) {
          console.log(value);
          api_graph_legend =
            '<li><i class="fa fa-square" style="color:' +
            value.color +
            '"></i>&nbsp;' +
            value.name +
            "</li>";
          console.log(api_graph_legend);
          $(".chart-legend-items").append(api_graph_legend);
        });

        $.each(campaign_table_data, function(key, value) {
          console.log(value);
          api_table_items = "<tr>";
          api_table_items +=
            '<td>&nbsp;<i class="fa fa-square" style="color:' +
            value.color +
            '"></i>&nbsp;</td>';
          api_table_items += "<td>" + value.name + "</td>";
          api_table_items +=
            "<td>&nbsp; + &nbsp;" + value.increased_value + "</td>";
          api_table_items += "<td>" + value.current + "</td>";
          api_table_items += "<td>" + value.percentage + "</td>";
          api_table_items += "</tr>";
          $(".table-graph-items-content").append(api_table_items);
        });

        var chart = new Highcharts.Chart({
          chart: {
            renderTo: "chart-container",
            type: "bar"
          },
          title: {
            text: null
          },
          xAxis: {
            title: {
              text: "Choices"
            },
            type: "category"
          },
          yAxis: {
            tickInterval: 1,
            title: {
              text: "Number of Votes"
            }
          },
          plotOptions: {
            series: {
              //pointWidth: 20,
            }
          },
          legend: {
            enabled: true,
            labelFormatter: function() {
              return this.name;
            }
          },
          series: campaign_graph_data,
          credits: false,
          tooltip: {
            borderColor: "rgba(0,0,0)",
            backgroundColor: "rgba(0, 0, 0, 0.75)",
            useHTML: true,
            formatter: function() {
              return (
                " " +
                '<span style="color:white">Description: ' +
                this.point.description +
                "</span><br />" +
                '<span style="color:white">Current: ' +
                this.point.y +
                "</span><br />" +
                this.point.increased_value
              );
            }
          }
        });
      }
    });
  }
});

这工作正常,但不是我想要的,因为图表总是重绘。我已经研究过使用setData()函数,但我认为它需要你知道图表的确切索引,但如果我将数据转换为单个系列,则会产生我想要的结果。至于我的问题,有没有办法使用highcharts设置数据函数多个系列/点?

jquery highcharts
1个回答
0
投票

我已经弄清楚了。我能够通过放置一个虚拟数据占位符来操纵它。使用此代码将阻止图表执行重绘动画,而只是更新数据。

$(document).on('change','.campaign-dropdown', function(){
		selected_campaign = $(this).val();
		getGraphDashboardBase(selected_campaign);

	});

	function getGraphDashboardBase(id){
		$.ajax({
			url:  window.apiURL + 'tally/api/dashboard/campaign/'+id,
			type: 'GET',
			contentType: 'application/json; charset=utf-8',
			headers:{
				Authorization: window.currentUser+' '+window.apiKey
			},
			dataType: 'json',

			success: function(response) {
				console.log(response.data);
				
				seriesLength = response.data.length;
				seriesPlaceholdArray = [];
				chartConfig.series = [];
				for( i = 0; i < seriesLength; i++){
					createChart(response.data[i].Choice,[],response.data[i].option_color);
				}
				getCampaignbyId(id);
				window.clearInterval(window.poll_fetch);
				window.poll_fetch = setInterval (function(){
					getCampaignbyId(id);
				},10000);

			}
		});
	}

	function getCampaignbyId(id){
		$.ajax({
			url:  window.apiURL + 'tally/api/dashboard/campaign/'+id,
			type: 'GET',
			contentType: 'application/json; charset=utf-8',
			headers:{
				Authorization: window.currentUser+' '+window.apiKey
			},
			dataType: 'json',

			success: function(response) {
				console.log(response.data);
				campaign_graph_data = [];
				campaign_graph_legend_name = [];
				campaign_table_data = [];
				response_graph_api_data = [];
				$.each(response.data, function(i,value){
					var inc_value;
					if( value.increase != 0){
						inc_value = '<span style="color:green">('+' + '+value.increase+' increase )</span>';
					}
					else{
						inc_value ='';	
					}

					response_graph_api_data = [{

						y:parseInt(value.current),
						name:value.Choice,
						description:value.Description,
						color:value.option_color,
						increased_value:inc_value	
					}]
					response_table_api_data = {
						name:value.Choice,
						color:value.option_color,
						current:value.current,
						increased_value:value.increase,
						percentage:value.percentage,
						previous:value.previous
					}
					campaign_graph_data.push(response_graph_api_data);
					campaign_table_data.push(response_table_api_data);
					chart.series[i].setData(response_graph_api_data);
					
				});
				//chart.series[0].setData(campaign_graph_data);

				/*marginTop + marginBottom + ((pointWidth * barCount) * (1 + groupPadding + pointPadding));*/
				//pointCount  = chart.series.length;
				var pointCount = chart.series.length;
				chartHeight = marginTop + marginBottom + ((pointWidth * pointCount) *(1 + groupPadding + pointPadding));

				chart.setSize(null,chartHeight);

				

				$('.chart-legend-items').empty();
				$('.table-graph-items-content').empty();

				$.each(campaign_graph_data,function(key,value){
					api_graph_legend ='<li><i class="fa fa-square" style="color:'+value.color+'"></i>&nbsp;'+value.name+'</li>';
					console.log(api_graph_legend);
					$('.chart-legend-items').append(api_graph_legend);
				});

				$.each(campaign_table_data,function(key,value){
					api_table_items = '<tr>';
					api_table_items +='<td>&nbsp;<i class="fa fa-square" style="color:'+value.color+'"></i>&nbsp;</td>';
					api_table_items +='<td>'+value.name+'</td>';
					api_table_items +='<td>&nbsp; + &nbsp;'+value.increased_value+'</td>';
					api_table_items +='<td>'+value.current+'</td>';
					api_table_items +='<td>'+value.percentage+'</td>';
					api_table_items +='</tr>';
					$('.table-graph-items-content').append(api_table_items);
				});

				

			}
		});
	}

	var pointWidth = 20;
  	var marginTop = 70;
  	var marginRight = 10;
  	var marginBottom = 50;
  	var marginLeft = 100;
  	var groupPadding = 0;
  	var pointPadding = 0.3;

	var chartConfig = {
		chart: {
			renderTo: 'chart-container',
			type: 'bar',
		},
		title: {
			text: null
		},
		xAxis: {
			title: {
				text: 'Choices'
			},
			type: "category"
		},
		yAxis:{
			tickInterval:1,
			title:{
				text: 'Number of Votes'
			}
		},
		legend:{
			enabled:true,
			symbolRadius:0
		},
		plotOptions:{
			bar:{
				grouping:false,
				pointPadding:pointPadding,
				groupPadding:groupPadding,
				pointWidth:pointWidth

			},
		},
		credits:false,
		series:[],
		tooltip: {
			borderColor:'rgba(0,0,0)',
			backgroundColor: 'rgba(0, 0, 0, 0.75)',
			useHTML:true,
			formatter: function() {return ' ' +
			'<span style="color:white">Description: '+ this.point.description + '</span><br />' +
			'<span style="color:white">Current: ' + this.point.y + '</span><br />'+
			this.point.increased_value;

		}
	}
}

function createChart(name,data,color){	
	
	tempGraphArray = {
		name:name,
		data:data,
		color:color
	}

	chartConfig.series.push(tempGraphArray);
	chart = new Highcharts.Chart(chartConfig);
	
}
© www.soinside.com 2019 - 2024. All rights reserved.