javascript - for loop to generate charts (amchart)

旧城冷巷雨未停 提交于 2019-12-04 16:54:12

As many comments correctly pointed out, you should probably start with rethinking your approach to data loading. Passing SQL queries in from client-side is asking for trouble. Will you be able to properly sanitize your queries to guard against malicious code? You can't be sure.

It's far more reasonable to move your DB access layer to PHP. You can pass in parameters needed for PHP script running on server to identify what needs to be loaded from DB and construct and execute actual SQL queries.

I.e.: query_db.php?chart_id=5

It would be up for PHP script to determine what to do. Given that you're currently using PHP to format those SQL queries, I can hardly image it can be a problem.

This brings us to another issue. Your current setup will run multiple AJAX requests simultaneously. While it's probably OK in the example you posted which has two charts, it can bog down the performance if you you have, say, 30 charts you need to load data for.

The solution would be to daisy-chain the loading. Do not start loading of another chart, until the previous one finishes loading. I.e.:

var charts = [ {
  "name": "chart1",
  "div": "plot1",
  "config": clone( chartConfigLineOne ),
  "query": <? php echo json_encode( $db_query_1 ) ?>
}, {
  "name": "chart2",
  "div": "plot2",
  "config": clone( chartConfigLineOne ),
  "query": <? php echo json_encode( $db_query_2 ) ?>
} ];

// do whatever modifications to each chart's config you need here
// ...

// function that creates the chart
function processNextChart() {
  if ( charts.length ) {
    var chart = charts.shift();
    $.ajax( {
      type: 'POST',
      url: "query_db.php",
      data: {
        'db_que': chart.query
      },
      dataType: 'json',
      context: document.body,
      global: false,
      async: true,
      success: function( data ) {
        chart.config.dataProvider = data;
        chartObj = AmCharts.makeChart( chart.div, chart.config );
        setTimeout( processNextChart, 100 );
      }
    } );
  }
}

// process first chart
processNextChart();

Please note how I simplified your whole chart array with a single array that holds all applicable data.

Please note, that the above code is not live-tested and is meant as a guiding point for your own implementation.

Do not make ajax calls inside the for loop. It's a burden on server. The less calls you make, the more responsive is your ui. So, the better way to implement what you want is to get all data for all graphs in one ajax call and on success to iterate through the data building your graphs with AmCharts.makeChart.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!