如何使用jQuery ajax()绘制Google Chart?

时间:2012-04-02 08:25:46

标签: php jquery arrays charts

我有这个代码来生成图表:

<script type="text/javascript">

     google.load('visualization', '1.0', {'packages':['corechart']});
    $(document).ready(function() {

    $('.show_chart').click(function(){
        var sku = $(this).attr("data-sku");
        var vid = $(this).attr("data-vid");

        $.ajax({
             type: "POST",
             url:"../ajax/priceChart.php", 
             async: false,
             dataType:'text',//moment google apito mai ne go zaredi !
             data: {'sku':sku,'vid':vid},
             success:function(vals){
                 var vals = vals;
                 $(".dialog").dialog({
                    modal:true,
                    buttons: { "Cancel": function() { $(this).dialog("close"); } }
                });


drawChart(vals);
                return false;



            },
                error:function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);
                    alert(thrownError);
                }  
        });       
    }); 



    })
function drawChart(vals) {
        console.log(1);
        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Date');
        data.addColumn('number', 'New');
        data.addColumn('number', 'Old');
        data.addRows([
         // ['2012-03-29 16:36:58', 313.99000, 314.00000],
         // ['2012-03-29 16:36:58', 313.99000, 314.00000]
            vals

        ]);


        // Set chart options
        var options = {'title':'PriceChart'};

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
        console.log(4);
      }  

</script>

PHP的返回结果是:

foreach ($arr as $v){
    $ts = $v['timestamp'];
    $p = $v['price'];
    $po = $v['price_old'];
    $resp[] = "[" 
                                    . "'$ts'" . ", "
                                    . "$p" . ", "
                                    . "$po"
                                    . "]";
}

echo implode(',',$resp);

如果我使用php文件中的返回结果Google Chart不起作用。如果我使用默认值谷歌图表工作。问题出在哪儿 ?在此先感谢,我为我的英语道歉!

1 个答案:

答案 0 :(得分:1)

在绘图功能中,您已将New和Old定义为数字。你从PHP获得了两倍。

foreach ($arr as $v){
$ts = $v['timestamp'];
$p = (int) $v['price'];
$po = (int) $v['price_old'];
$resp[] = "[" 
                                . "'$ts'" . ", "
                                . "$p" . ", "
                                . "$po"
                                . "]";
}

echo implode(',',$resp);

请尝试此代码。

希望得到这个帮助。

〜ķ