javascript - 将变量传递给外部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
},]
},
任何人都可以帮助我吗
解决方案
您不能将 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
},]
},
推荐阅读
- python - 如何用分号分隔 CSV 文件?
- mysql - mySql - 在特定城市附近寻找客户
- php - “mysqli_result 类的对象无法转换为字符串”是否有解决方案?
- php - 消除
WooCommerce 中产品属性的标签
- jquery - 与下一个和上一个分页
- python - Pandas 数据框中的新列存在问题
- c# - 尝试向 Asp.Net Web Api 2 控制器方法提交长字符串时出现错误请求
- c - 使用 C 中的宏访问数组索引
- python - 有没有办法使用图像 URL 在电子邮件正文中显示图像
- bi-publisher - 重音字符在 BI Publisher PDF 输出中未正确显示