javascript - for 循环生成图表(amchart) [英] javascript - for loop to generate charts (amchart)

查看:32
本文介绍了javascript - for 循环生成图表(amchart)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码一次性生成多个折线图.但是,它不起作用.使用 for/while 或任何其他循环机制生成图形的最佳方法是什么?我有很多图表要生成.

Am trying to generate multiple line charts at one go using the code below. However, it isn't working. What would be the best way to generate graphs using a for/while or any other looping mechanism? I have many charts to generate.

   var db_query = Array();
    db_query[1] = <?php echo json_encode($db_query_1) ?>;
    db_query[2] = <?php echo json_encode($db_query_2) ?>;

    var chartConfig1 = clone(chartConfigLineOne);
    var chartConfig2 = clone(chartConfigLineOne);

    for(var i=1, len=2; i <= len; i++) {
        /* chart initialization */
        var chart_num = "chart" + i.toString();
        var plot_num =  "plot" + i.toString();
        var chartConfig_num = "chartConfig" + i.toString();
        /*alert(chart_num);
        alert(plot_num);
        alert(chartConfig_num);*/
        chart_num = AmCharts.makeChart(plot_num, chartConfig_num);

        $.ajax({
            type: 'POST',
            url: "query_db.php",
            data: {'db_que': db_query[i]},
            dataType: 'json',
            context: document.body,
            global: false,
            async:  true,
            success: function(data) {
                //alert(data);
                chart_num.dataProvider = data;
                chart_num.validateNow();
            }
        });
    }

更新代码

        <script type="text/javascript">

            var chartNameList = ['chart1','chart2'];
            var divId = ['plot1','plot2'];
            var configList = ['chartConfig1','chartConfig2'];
            var dbQuery = [];

            var chartConfig1 = clone(chartConfigLineOne);
            var chartConfig2 = clone(chartConfigLineOne);

             dbQuery[0] = <?php echo json_encode($db_query_1) ?>;
             dbQuery[1] = <?php echo json_encode($db_query_2) ?>;

            /* chart initialization */
            for(var i =0; i < 2; i += 1)   {
                //window["chart"+i] = createChartObj(divId[i],configList[i]);
                execDbQuery(divId[i],configList[i],dbQuery[i],chartNameList[i]);
            }
        </script>

/**
 * Execute of DB query
 */

function execDbQuery(divId, configObj, dbQuery, chartObj) {
    chartObj = AmCharts.makeChart(divId, configObj);
    $.ajax({
        type: 'POST',
        url: "query_db.php",
        data: {'db_que': dbQuery},
        dataType: 'json',
        context: document.body,
        global: false,
        async:  true,
        success: function(data) {
            //alert(data);
            chartObj.dataProvider = data;
            chartObj.validateNow();
        }
    });
} 

推荐答案

正如许多评论正确指出的那样,您可能应该从重新思考数据加载方法开始.从客户端传递 SQL 查询是自找麻烦.您能否正确清理您的查询以防范恶意代码?你不能确定.

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.

将您的数据库访问层移至 PHP 更为合理.您可以传入服务器上运行的 PHP 脚本所需的参数,以识别需要从数据库加载的内容,并构建和执行实际的 SQL 查询.

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.

即:query_db.php?chart_id=5

由 PHP 脚本决定要做什么.鉴于您目前正在使用 PHP 来格式化这些 SQL 查询,我很难想象这可能是一个问题.

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.

这给我们带来了另一个问题.您当前的设置将同时运行多个 AJAX 请求.虽然在您发布的包含两个图表的示例中可能没问题,但如果您有 30 个图表需要加载数据,则可能会降低性能.

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.

这篇关于javascript - for 循环生成图表(amchart)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆