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

标签 javascript php jquery ajax

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

相关文章:

javascript - 在 foreach 中加载所有项目后,Knockoutjs 组件回调

PHP 变量函数数组值

jquery - 将多个 JSON 对象传递给 MVC3 操作方法

jQuery 与 Firefox 不兼容

php - 使用 aes_decrypt 和 fetch_assoc

javascript - 数到一个高数的持续时间

javascript - 如何从相同 ng-options 的其他用途中删除 select ng-options

javascript - 如何将文件附加到 html 'file' 元素以使用 jquery/js 上传?

javascript - 使用 setPosition 更改位置时 Google 标记消失

php - 从 MySQL 中选择特定年份