我想在图表上显示每月注册的新生人数和在线学生的人数。我得到了数据,但我不知道如何将数据转换到js文件中来绘制图表。我的js文件在public目录中,我已经连接到js文件,但我不知道如何向它传递数据。
我的控制器来获取数据
class DashboardController extends AdminBaseController
{
public function index ()
{
$month = 1;
$totalNewStudent = [];
$totalOnline = [];
$totalActive = [];
for($i = $month; $i < 13; $i++) {
//count new students
$newStudents = Member::where('member_type_id',1)-
>whereMonth('created_at', $i)->get();
$totalNewStudent[$i] = $newStudents->count();
//students online
$onlStudents = Member::where('member_type_id',1)-
>whereMonth('updated_at', $i)->get();
$totalOnline[$i] = $onlStudents->count();
// count card active
$act = Order::where('status', "active")->whereMonth('updated_at', $i)-
>get();
$totalActive[$i] = $act->count();
return view('admin.dashboard.index', compact('totalNewStudent','totalOnline','totalActive '));
}
}
}查看admin.dashboard.index
<div class="card-body collapse in">
<div class="card-block">
<div id="products-sales" class="height-300"></div>
</div>
</div>Js文件
var months = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
Morris.Area({
element: 'products-sales',
data: [{
month: '2017-01',
newstudent: 0,
online: 0,
}, {
month: '2017-02',
newstudent: 240,
online: 0,
}, {
month: '2017-03',
newstudent: 0,
online: 0,
}, {
month: '2017-04',
newstudent: 0,
online: 190,
}, {
month: '2017-05',
newstudent: 0,
online: 25,
}, {
month: '2017-06',
newstudent: 0,
online: 150,
}, {
month: '2017-07',
newstudent: 0,
online: 0,
},{
month: '2017-08',
newstudent: 80,
online: 0,
},{
month: '2017-09',
newstudent: 0,
online: 0,
},{
month: '2017-10',
newstudent: 0,
online: 0,
},{
month: '2017-11',
newstudent: 300,
online: 0,
},{
month: '2017-12',
newstudent: 0,
online: 0,
}],
xkey: 'month',
ykeys: ['newstudent', 'online'],
labels: ['New Student', 'Online'],
xLabelFormat: function(x) { // <--- x.getMonth() returns valid index
var month = months[x.getMonth()];
return month;
},
dateFormat: function(x) {
var month = months[new Date(x).getMonth()];
return month;
},
behaveLikeLine: true,
ymax: 300,
resize: true,
pointSize: 0,
pointStrokeColors:['#00B5B8', '#FA8E57', '#F25E75'],
smooth: true,
gridLineColor: '#E4E7ED',
numLines: 6,
gridtextSize: 14,
lineWidth: 0,
fillOpacity: 0.9,
hideHover: 'auto',
lineColors: ['#00B5B8', '#FA8E57', '#F25E75']
});发布于 2019-10-05 00:44:57
最简单的方法:
将您的变量添加到input元素:
<input type="hidden" value="{{ $my_variable }}" id="my-variable">使用js获取值:
let myVar = $("#my-variable").val();就我个人而言,我不喜欢这种方法。最好的方法是使用ajax并直接从服务器获取变量。
希望能有所帮助。
发布于 2019-10-06 00:10:53
将其作为PHP变量返回给将包含JS文件的视图
然后将此代码添加到视图中
// Do this before importing the JS file
var data = {!! json_encode($php_var) !!};在较新的laravel版本中
var data= @json($php_var);数据将在JS文件中可用
或者,您可以使用此包
https://stackoverflow.com/questions/58240294
复制相似问题