通过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对象发送到ajax的方法

 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); 

但是,如果我在形成的var d graph和显示的数据的位置使用这样的虚拟数据。 我想了解这个虚拟数据与从数据库中获取的数据之间的区别。

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

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 + " – "); });