通过ajax为flot.js提供的数据显示未定义


Data supplied for flot.js via ajax says undefined

在下面的脚本中,我从数据库中获取数据以形成折线图。但是数据显示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 + " – ");
});