将PHP Array推入AJAX响应到JQuery数组中

时间:2014-12-26 07:27:30

标签: javascript php jquery arrays ajax

我无法将MySQL查询的结果输出为图表的数据集。我不知道如何将结果传递给一个简单的数组。它在PHP中回应良好并且ajax请求有效,但(我假设)它无法格式化为数组的正确jquery / javascript格式。以下是我的代码的要点:

绘制图表的主页上的JavaScript部分:

<script>
    var randomScalingFactor = function(){ return Math.round(Math.random()*100)};

    var lineChartData = {
        labels : ["January","February","March","April","May","June","July"],
        datasets : [
            {
                label: "Fast Signal",
                fillColor : "rgba(220,220,220,0.2)",
                strokeColor : "rgba(220,220,220,1)",
                pointColor : "rgba(220,220,220,1)",
                pointStrokeColor : "#fff",
                pointHighlightFill : "#fff",
                pointHighlightStroke : "rgba(220,220,220,1)",
                data : getFast()
            },
            {
                label: "Slow Signal",
                fillColor : "rgba(151,187,205,0.2)",
                strokeColor : "rgba(151,187,205,1)",
                pointColor : "rgba(151,187,205,1)",
                pointStrokeColor : "#fff",
                pointHighlightFill : "#fff",
                pointHighlightStroke : "rgba(151,187,205,1)",
                data : getSlow()
            }
        ]

    }

window.onload = function(){
    var ctx = document.getElementById("canvas").getContext("2d");
    window.myLine = new Chart(ctx).Line(lineChartData, {
        responsive: true
    });
}


</script>

主页上的AJAX,在图表加载时调用:

<script type="text/javascript">
function test(){
    alert("test");
    }
function getAll(){
            $.ajax({
                type:"POST",
                url:"dataproc.php",
                data:{  action: true,
                        all: true

                },
                success:function(data){
                     $("#dataDiv").html(data);
                }
            });
        }
function getFast(){
            $.ajax({
                type:"POST",
                url:"dataproc.php",
                data:{  action: true,
                        fast: true

                },
                success:function(data){
                     $("#fastDiv").html(data);
                     return data;
                }
            });
        }
function getSlow(){
            $.ajax({
                type:"POST",
                url:"dataproc.php",
                data:{  action: true,
                        slow: true

                },
                success:function(data){
                     $("#slowDiv").html(data);
                     return data;
                }
            });
        }
function getHisto(){
            $.ajax({
                type:"POST",
                url:"dataproc.php",
                data:{  action: true,
                        histo: true

                },
                success:function(data){
                     $("#histoDiv").html(data);
                     return data;
                }
            });
        }
</script>

以及AJAX调用的远程页面:

<?php
if(isset($_POST['action'])){
    if(isset($_POST['all'])){
        define("DB_DSN", "mysql:host=localhost;dbname=BTCUSD"); //db conn
        define("DB_USERNAME","prices"); //db user
        define("DB_PASSWORD","********"); // db pass
        try {
            //echo "Current Price: $".$current;
            $con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
            $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "SELECT * FROM 5Minute ORDER BY timestamp ASC";
            $stmt = $con->prepare($sql);
            $stmt->execute();
            $valid = $stmt->fetchAll();
            $con = null;

            if($valid){
                foreach($valid as $res){
                    $prices[] = (float)$res["price"];
                }
                $macdArr = trader_macd($prices,12,26,9);
                if(end($macdArr[0]) &&  end($macdArr[1]) && end($macdArr[2])){
                    echo json_encode($macdArr, JSON_NUMERIC_CHECK);



                }
            }
        }catch(PDOException $e){
            echo "Error: ".$e->getMessage();
        }
        $con = null;
    }
    if(isset($_POST['fast'])){
        define("DB_DSN", "mysql:host=localhost;dbname=BTCUSD"); //db conn
        define("DB_USERNAME","prices"); //db user
        define("DB_PASSWORD","*******"); // db pass
        try {
            //echo "Current Price: $".$current;
            $con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
            $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "SELECT * FROM 5Minute ORDER BY timestamp ASC";
            $stmt = $con->prepare($sql);
            $stmt->execute();
            $valid = $stmt->fetchAll();
            $con = null;

            if($valid){
                foreach($valid as $res){
                    $prices[] = (float)$res["price"];
                }
                $macdArr = trader_macd($prices,12,26,9);
                if(end($macdArr[0]) &&  end($macdArr[1]) && end($macdArr[2])){
                    $fastArr = array();
                    foreach($macdArr[0] as $fastVal){
                        $fastArr[] = $fastVal;
                    }
                    echo json_encode($fastArr, JSON_NUMERIC_CHECK);;
                }
            }
        }catch(PDOException $e){
            echo "Error: ".$e->getMessage();
        }
        $con = null;
    }
    if(isset($_POST['slow'])){
        define("DB_DSN", "mysql:host=localhost;dbname=BTCUSD"); //db conn
        define("DB_USERNAME","prices"); //db user
        define("DB_PASSWORD","********"); // db pass
        try {
            //echo "Current Price: $".$current;
            $con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
            $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "SELECT * FROM 5Minute ORDER BY timestamp ASC";
            $stmt = $con->prepare($sql);
            $stmt->execute();
            $valid = $stmt->fetchAll();
            $con = null;

            if($valid){
                foreach($valid as $res){
                    $prices[] = (float)$res["price"];
                }
                $macdArr = trader_macd($prices,12,26,9);
                if(end($macdArr[0]) &&  end($macdArr[1]) && end($macdArr[2])){
                    $slowArr = array();
                    foreach($macdArr[1] as $slowVal){
                        $slowArr[] = $slowVal;
                    }
                    echo json_encode($slowArr, JSON_NUMERIC_CHECK);;
                }
            }
        }catch(PDOException $e){
            echo "Error: ".$e->getMessage();
        }
        $con = null;
    }
    if(isset($_POST['histo'])){
        define("DB_DSN", "mysql:host=localhost;dbname=BTCUSD"); //db conn
        define("DB_USERNAME","prices"); //db user
        define("DB_PASSWORD","*******"); // db pass
        try {
            //echo "Current Price: $".$current;
            $con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
            $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "SELECT * FROM 5Minute ORDER BY timestamp ASC";
            $stmt = $con->prepare($sql);
            $stmt->execute();
            $valid = $stmt->fetchAll();
            $con = null;

            if($valid){
                foreach($valid as $res){
                    $prices[] = (float)$res["price"];
                }
                $macdArr = trader_macd($prices,12,26,9);
                if(end($macdArr[0]) &&  end($macdArr[1]) && end($macdArr[2])){
                    $histoArr = array();
                    foreach($macdArr[2] as $histoVal){
                        $histoArr[] = $histoVal;
                    }
                    echo json_encode($histoArr, JSON_NUMERIC_CHECK);;
                }
            }
        }catch(PDOException $e){
            echo "Error: ".$e->getMessage();
        }
        $con = null;
    }
}
?>

当我将输出作为成功的AJAX查询回显到div时,它显示如下:

[ - 1.066,-0.995,-0.927,-0.863,-0.804,-0.746,-0.739,-0.687]

图表脚本中数据字段的格式正确,但图表不会绘制。

我认为&#34;返回数据是错误的;&#34;在ajax调用之后将数组结果传递回jquery / javascript的正确方法是什么?

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

你应该在ajax调用结束后初始化图形。

例如:

var data1;
var data2;

$(document).ready(function() {
    //get the first data
    .ajax({
        type:"POST",
        url:"dataproc.php",
        data:{  action: true,
                slow: true

        },
        success:function(data){
             data1 = data;
             getSecondData(); //call to get second data
        }
    }
});

function getSecondData()
{
    .ajax({
        type:"POST",
        url:"dataproc.php",
        data:{  action: true,
                histo: true

        },
        success:function(data){
             data2 = data;
             drawGraph(); //now draw
        }
    }
}

function drawGraph()
{
    //draw graph with data 1 and data2
}