首页 > 解决方案 > 将变量传递给外部js文件-laravel

问题描述

我正在使用 Laravel,我想将变量传递给外部 js 文件,这里是控制器代码:

 public function reports()
  {         

   $phone = Product::where('type','phone')->where('year','2018')->get(); 
                     $phoneCount =count($phone);
   $laptop = Product::where('type','laptop')->where('year','2018')->get(); 
                     $laptopCount =count($laptop);

  }

        return view('report', ['phone' => $phoneCount,'laptop'=>$laptopCount ]);

这是外部chart.js代码,但它不起作用

data: {
      labels: ["phone","laptop"],
      datasets: [
        {
          label: "Processes Completed",
          backgroundColor: "rgb(76, 132, 255)",
          borderColor: "rgba(76, 132, 255,0)",
          data:[{{$phoneCount}},{{$laptopCount}}] ,
          pointBackgroundColor: "rgba(76, 132, 255,0)",
          pointHoverBackgroundColor: "rgba(76, 132, 255,1)",
          pointHoverRadius: 3,
          pointHitRadius: 30
        },]
    },

任何人都可以帮助我吗

标签: javascriptlaravelcharts

解决方案


您不能将 PHP 变量.js直接传递给文件。但是你可以将它传递给视图,在那里你使用 src chart.js,然后你可以使用变量 with chart.js。像这个例子:

报告.blade.php

// make sure you define this variable before load chart.js
<script>
   var phoneCount = {{ phoneCount }};
   var laptopCount = {{ laptopCount }};
</script>

图表.js

data: {
      labels: ["phone","laptop"],
      datasets: [
        {
          label: "Processes Completed",
          backgroundColor: "rgb(76, 132, 255)",
          borderColor: "rgba(76, 132, 255,0)",
          data:[phoneCount, laptopCount] ,
          pointBackgroundColor: "rgba(76, 132, 255,0)",
          pointHoverBackgroundColor: "rgba(76, 132, 255,1)",
          pointHoverRadius: 3,
          pointHitRadius: 30
        },]
    },

推荐阅读