OctoberCMS - 如何在javascript中提供组件数据

时间:2017-10-31 06:20:12

标签: javascript php jquery octobercms

我需要动态填充仪表板主题的数据,但我不确定如何执行此操作。到目前为止,我的代码看起来像这样。

组件:

public $orders;

public function onRun() {
    $this->orders = $this->loadOrders();
}

protected function loadOrders() {
    $all_customers = Db::table('customers')->get();

    foreach ($all_customers as $customer) {

    }

    $orders = Db::table('orders')->where('company_name', $customer->company_name)->count();

    return $orders;
}

从这里我得到系统中该订单的数量,该订单工作正常,但它是我正在努力的下一部分。 这是我的javascript:

var PIECHART = $('#pieChart');
var orders = ** This is where I am lost **;
var quotes = ** This is where I am lost **;
var invoices = ** This is where I am lost **;
var myPieChart = new Chart(PIECHART, {
    type: 'doughnut',
    data: {
        labels: [
            "Orders",
            "Quotes",
            "Invoices"
        ],
        datasets: [
            {
                data: [orders, quotes, invoices],
                borderWidth: [1, 1, 1],
                backgroundColor: [
                    brandPrimary,
                    "rgba(75,192,192,1)",
                    "#FFCE56"
                ],
                hoverBackgroundColor: [
                    brandPrimary,
                    "rgba(75,192,192,1)",
                    "#FFCE56"
                ]
            }]
    }
});

我很确定解决方案是相当直接的,但我是一个菜鸟:P

1 个答案:

答案 0 :(得分:1)

我们假设您在页面

中直接使用此组件

所以你需要做的就是尝试使用

public function onRun() {
    $this->page['orderCount'] = $this->loadOrders();
}

现在在您的页面中,您需要将此变量提供给js

<script>
// we don't want to pollute global scope so we add our name space
var myComponent = myComponent || {}
// now we add our value to it 
myComponent['orderCount'] = {{ orderCount }};
</script>

上面的代码会生成,假设我们得到的计数器是15然后

myComponent['orderCount'] = 15;

现在在你的javascript中你可以像

一样使用它
var PIECHART = $('#pieChart');
var orders = myComponent['orderCount']; // or myComponent.orderCount
var quotes = ** This is where I am lost **;
var invoices = ** This is where I am lost **;

这适用于数字但如果你还需要将数组共享到java脚本,你需要将它转换为JSON然后你可以使用它

如果您需要进一步的帮助,请告诉我