带有堆栈插件的Flotchart,处理空数组

时间:2014-06-03 01:34:26

标签: ajax json charts stack flot

我正在使用带有堆栈插件的flotchart(http://www.flotcharts.org/)来绘制包含多个系列的图形,并且我正在通过AJAX调用从php脚本中检索MySQL数据库中的数据。问题是由于某些原因,几个系列的数据可能不可用或存在,因此MySQL将返回一个空结果,然后AJAX调用返回一个空数组,这会导致图表在空系列之后不绘制任何内容。

以下是我正在使用的代码:

   var graph_range =10;
    var now = Math.round(+new Date()/1000) - (60*graph_range);
  var jsData = new Object();
  var d1, d2, d3  = new Object();
  $.ajaxSetup({ async: false  });
    $.getJSON('getjson.php',{id: '2', time: now, single: 'down'},function(result){ d1= result; });
    $.getJSON('getjson.php',{id: '4', time: now, single: 'down'},function(result){ d2= result; });
    $.getJSON('getjson.php',{id: '7', time: now, single: 'down'},function(result){ d3= result; });
    $.getJSON('getjson.php',{id: '8', time: now, single: 'down'},function(result){ d1= result; });
    $.getJSON('getjson.php',{id: '10', time: now, single: 'down'},function(result){ d2= result; });
    $.getJSON('getjson.php',{id: '11', time: now, single: 'down'},function(result){ d3= result; });
  $.ajaxSetup({ async: true  });
    var vals= [ d1, d2, d3];


    function plotWithOptions() {
        $.plot("#flotchart", vals , {
            series: {
                stack: true,
                lines: {
                    show: true,
                    fill: true,
                    steps: 8
                }
            }
        });
    }

    plotWithOptions();

当我将堆栈设置为false时,除了没有数据的系列(返回空数组)之外,它的工作正常。但当我把它变成我需要的“真实”时,会绘制出非常多的系列,但是当一个空数组出现时,之后的所有内容都不会被绘制出来。

1 个答案:

答案 0 :(得分:3)

你可以替换

var vals= [ d1, d2, d3];

var vals = [];
if (d1 != [])
    vals.push(d1);
if (d2 != [])
    vals.push(d2);
if (d3 != [])
    vals.push(d3);

因此,只有非空数组才会添加到绘图数据中。

顺便说一句:你用第四到第六getJSON次电话覆盖d1,d2,d3。那是你想做的吗?然后,您可以在没有前三个getJSON调用的情况下执行操作,因为它们不会为您执行任何操作。