将变量从PHP传递到Javascript图表

时间:2015-05-01 11:38:23

标签: javascript php json

我从Json格式的php中检索信息,以便在我的图表中传递它,这是通过javascript工作,我已经正确地从php传递到javascript,但是当我在图表中使用这个javascript时,图表停止工作

$result = mysql_query("select * from employee", $db);  

//Create an array
$json_response = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    $row_array['date'] = $row['date'];
    $row_array['rate'] = $row['rate'];


    //push the values in the array
    array_push($json_response,$row_array);
} 
$all= json_encode($json_response);
echo($all);

//Close the database connection
mysql_close($db);

?>


<script >
    var data_from_php = '<?php echo $all; ?>';
    alert(data_from_php);


    var  data = [{
             "date":"2012-03-01",
            "rate":"6"
        }, {
            "date": "2012-03-02",
            "rate": "-10"
        }, {
            "date": "2012-03-03",
            "rate": "1"
        },
        {
            "date": "2012-03-03",
            "rate": "1"
        },
        {
            "date": "2012-03-04",
            "rate": "5"
        },
        {
            "date": "2013-03-05",
            "rate": "10"
        },
        {
            "date": "2013-04-03",
            "rate": "-5"
        },
        {
            "date": "2013-05-10",
            "rate": "-2"
        }]



    var chart = AmCharts.makeChart("chartdiv", {
        "type": "serial",
        "theme": "light",
        "marginTop":0,
        "marginRight": 80,
        "pathToImages": "http://www.amcharts.com/lib/3/images/",
        "dataProvider": data,
        "valueAxes": [{
            "axisAlpha": 0,
            "position": "left"
           }],

好吧,我使用Json格式的数据手册来查看图表是否正常工作,并提醒我从php收到的变量并将其转换为Javascript 一切顺利

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:3)

更改

var data_from_php = '<?php echo $all; ?>';

var data_from_php = <?php echo $all; ?>;