在下面的脚本中,我从数据库中获取数据以形成折线图。但是数据显示 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 图和显示的数据。我想了解这个虚拟数据和从数据库中获取的数据之间的区别。
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 + " – ");
});
关于javascript - 通过 ajax 为 flot.js 提供的数据表示未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33495669/