没有使用ajax返回的数据更新flot图表

时间:2014-10-01 05:02:23

标签: jquery ajax flot

我正在使用flot chart。当我从ajax返回的数据中分配值时,代码无效。(代码无法正常工作):

<script type="text/javascript">

$(document).ready(function () {
  get_data();
});
function get_data() { 
  var options = { 
    lines: {show: true}, 
    points: {show: true}, 
    legend: {show: true, backgroundColor: "#fff", noColumns: 4, 
                position: "nw"}, 
    yaxis: { min: 0 }, 
    xaxis: { tickDecimals: 0 }, 
    grid: {color:"#CCCCCC", backgroundColor: "#fffaff"} 
  }; 
var start_date="September 14, 2014";
var user_group="USG0001";
var start_time=0;
var end_time=1200;
$.ajax({type:'POST',url:'....'}).done(function(result){

      { 
        plot = $.plot($("#placeholder"), result, options); 
      } 
  }); 
} 
</script>
</head>

<body>
    <div id="placeholder"></div>
</body>

如果我直接分配它,而不是传递ajax数据的结果,它可以工作:(工作代码

<script type="text/javascript">


$(document).ready(function () {
  get_data();
});
function get_data() { 
  var options = { 
    lines: {show: true}, 
    points: {show: true}, 
    legend: {show: true, backgroundColor: "#fff", noColumns: 4, 
                position: "nw"}, 
    yaxis: { min: 0 }, 
    xaxis: { tickDecimals: 0 }, 
    grid: {color:"#CCCCCC", backgroundColor: "#fffaff"} 
  }; 
var start_date="September 14, 2014";
var user_group="USG0001";
var start_time=0;
var end_time=1200;
$.ajax({type:'POST',url:'.....'}).done(function(result){

      { 
        result=[{"label":"meter1","data":[[0,0],[1,194],[2,223],[3,182],[4,201],[5,213],[6,206],[7,182],[8,266],[9,246],[10,238],[11,248],[12,210]]},{"label":1,"data":[[0,0],[1,98],[2,97],[3,100],[4,96],[5,94],[6,100],[7,94],[8,95],[9,99],[10,104],[11,98],[12,99]]},{"label":2,"data":[[0,0],[1,0],[2,0],[3,0],[4,0],[5,1],[6,12],[7,13],[8,35],[9,43],[10,44],[11,49],[12,43]]},{"label":3,"data":[[0,0],[1,7],[2,6],[3,7],[4,6],[5,7],[6,7],[7,6],[8,44],[9,59],[10,56],[11,46],[12,32]]},{"label":4,"data":[[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,7],[9,25],[10,24],[11,17],[12,20]]},{"label":5,"data":[[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,1],[10,1],[11,23],[12,22]]},{"label":6,"data":[[0,0],[1,2],[2,2],[3,2],[4,2],[5,2],[6,2],[7,3],[8,13],[9,15],[10,16],[11,18],[12,19]]},{"label":7,"data":[[0,0],[1,0],[2,1],[3,0],[4,0],[5,1],[6,1],[7,1],[8,50],[9,106],[10,133],[11,135],[12,112]]},];
        plot = $.plot($("#placeholder"), result, options); 
      } 
  }); 
} 
</script>
</head>

<body>
    <div id="placeholder"></div>
</body>

如果我直接从ajax返回的数据中使用该值,为什么它不能正常工作呢?

ps:从ajax调用返回的数据与工作案例中指定的值相同。

1 个答案:

答案 0 :(得分:0)

我认为首先你需要在ready方法中定义plot。在ajax调用之后,你需要setData如下。再绘制一次。请参阅以下代码。

  $(document).ready(function(){
     var data = [];
     var plot = $.plot($("#placeholder"), data, options); // define   options
   $.ajax({type:'POST',url:'.....'}).done(function(result){
  { 
    plot.setData([{data:result}]);
    plot.setupGrid();
    plot.draw();
   }
});