如何将数据从控制器传递到cakephp中的js文件?

时间:2015-11-11 20:34:31

标签: jquery cakephp

jquery code

$("#pendingChart").sparkline([9, 11, 12, 13, 12, 13, 10], {
                type: 'bar',
                width: '100',
                barWidth: 6,
                height: '45',
                barColor: '#5C9BD1',
                negBarColor: '#e02222'
            });

这样可以正常工作并生成图形图表。但我想从控制器生成数据[9,11,12,13,12,13,10]并传递给jquery代码。我的控制器部分没问题。这是代码:

function loadPointChart() {
        $reseller = $this->Auth->user();
        if (count($reseller) > 0) {
            $api_key = $reseller['api_key'];
            $this->loadModel('Order');
            //  $info=$this->Order->find('all','conditions' => array('api_key'=>$api_key));

            $sql = "SELECT orders.id,orders.modified,orders.status,order_products.*  FROM orders
                LEFT JOIN order_products ON orders.id=order_products.order_id
                 WHERE orders.api_key = '$api_key' ORDER BY orders.modified ASC";

            $infos = $this->Order->query($sql);

            $return['points'] = $this->pointsCalculate($infos);

            $penaltyChart = json_encode($return['points']['penalty']);
            $pendingChart = json_encode($return['points']['pending']);
            $successChart = json_encode($return['points']['success']);
             echo $penaltyChart;
            $this->set(compact('penaltyChart'));
        }
    }

echo echo $ penaltyChart;正在打印我需要的确切格式数据:[4,3]

但我会将这些数据操作到我的jquery代码中。 我在filter之前调用了这个函数,以便在页面渲染之前初始化变量。

将数据加载到jquery部分我尝试如下:

$("#penaltyChart").sparkline(<?php echo $penaltyChart; ?>, {
                type: 'bar',
                width: '100',
                barWidth: 6,
                height: '45',
                barColor: '#F36A5B',
                negBarColor: '#e02222'
            });

它出错:Uncaught SyntaxError: Unexpected token <。任何的想法?

1 个答案:

答案 0 :(得分:1)

1。load_point_chart.ctp:

<script>$("#pendingChart").sparkline([<?php echo implode(",", $penaltyChart); ?>], {
            type: 'bar',
            width: '100',
            barWidth: 6,
            height: '45',
            barColor: '#5C9BD1',
            negBarColor: '#e02222'
        });</script>

2。load_point_chart.ctp:

echo "<script>$('#pendingChart').sparkline([" . implode(",", $penaltyChart) . "], {
        type: 'bar',
        width: '100',
        barWidth: 6,
        height: '45',
        barColor: '#5C9BD1',
        negBarColor: '#e02222'
    });</script>";
在加载load_point_chart.ctp文件之前

3。.js

<script>window.penaltyChart = [<?php echo implode(",", $penaltyChart); ?>]</script>

此代码包含您的.js,然后在您的.js中更改代码,如下所示:

$("#pendingChart").sparkline(window.penaltyChart, {
            type: 'bar',
            width: '100',
            barWidth: 6,
            height: '45',
            barColor: '#5C9BD1',
            negBarColor: '#e02222'
        });