2015-11-03 25 views
1

在下面的脚本中,我从数据库获取数据以形成线图。但数据表示undefined并且没有图形形成。通过ajax为flot.js提供的数据说undefined

var d; 
var arr = []; 

$(function() { 
    var data; 
    $.ajax({ 
     dataType: "json", 
     url: 'query_sales.php', 
     success: function(data){ 
      $.each(data, function(i, item) { 
       arr.push([item.datey, +item.bv]); 
      }); 
      d = arr; //JSON.stringify(arr); 
     } 
    }); 

    alert(d); //says undefined 

    $.plot("#placeholder", [d], { 
     xaxis: { mode: "time" } 
    }); 

    $("#whole").click(function() { 
     $.plot("#placeholder", [d], { 
      xaxis: { mode: "time" } 
     }); 
    }); 

    // Add the Flot version string to the footer 
    $("#footer").prepend("Flot " + $.plot.version + " – "); 
}); 

这是我如何查询数据库,并通过PHP脚本发送JSON对象阿贾克斯

date_default_timezone_set("Asia/Kuala_Lumpur"); 
$acceptedUser = new search(); 
$sales = $acceptedUser->get_sales_graph(); 
$before = array(); 
foreach($sales as $k=>$v) 
{ 
    $date = strtotime($v['as_of_date']) * 1000; 
    array_push($before, array("datey" => $date, "bv" => $v['total_bv'])); 
} 
echo json_encode($before); 

但是如果我在变种d图形成的地点和数据使用虚拟数据这样所示。我想了解这个虚拟数据与从数据库中获取的虚拟数据之间的区别。

var d = [[946699200000, 315.71], [949377600000, 317.45], [951969600000, 317.50], [957240000000, 315.86], [952056000000, 314.93], [983592000000, 313.19], [1033617600000, 313.34]]; 

回答

2

AJAX调用是异步的,所有依赖于它的响应的代码都必须放在回调函数中。试试这个:

var d; 
var arr = []; 

$(function() { 
    var data; 
    $.ajax({ 
     dataType: "json", 
     url: 'query_sales.php', 
     success: function(data){ 
      $.each(data, function(i, item) { 
       arr.push([item.datey, +item.bv]); 
      }); 
      d = arr; //JSON.stringify(arr); 

      console.log(d); // use console.log to debug 

      $.plot("#placeholder", [d], { 
       xaxis: { mode: "time" } 
      }); 

      $("#whole").click(function() { 
       $.plot("#placeholder", [d], { 
        xaxis: { mode: "time" } 
       }); 
      }); 
     } 
    }); 

    // Add the Flot version string to the footer 
    $("#footer").prepend("Flot " + $.plot.version + " – "); 
}); 
+0

谢谢你我现在明白了 – 112233