简体   繁体   English

在 laravel 中使用 foreach 循环 javascript

[英]Use foreach loop in javascript in laravel

I have data am looping from controller and i have a graph script and i want to loop that data in the script so that it can draw the graph based on that data我有数据从 controller 循环,我有一个图形脚本,我想在脚本中循环该数据,以便它可以根据该数据绘制图形

In controller i have在 controller 我有

$records = Products::select('price')->get();

and in blade i have在刀片中我有

<script>
window.onload = function () {

var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    theme: "light2",
    title:{
        text: "Simple Line Chart"
    },
    data: [{        
        type: "line",
        indexLabelFontSize: 16,
        dataPoints: [

            @foreach($records as $prc)
            { y: $prc->price},
            @endforeach


        ]
    }]
});
chart.render();

}
</script>

Original script原剧本

<script>
window.onload = function () {

var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    theme: "light2",
    title:{
        text: "Simple Line Chart"
    },
    data: [{        
        type: "line",
        indexLabelFontSize: 16,
        dataPoints: [
            { y: 500 },
            { y: 400 },
            { y: 250 },
            { y: 310 }
        ]
    }]
});
chart.render();

}
</script>

Its giving me a blank page, how can i go about doing it它给了我一个空白页,我该怎么做 go

Solution from @Aless55 works perfectly fine 来自@Aless55 的解决方案完美无缺

<script>
window.onload = function () {

var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    theme: "light2",
    title:{
        text: "Simple Line Chart"
    },
    data: [{        
        type: "line",
        indexLabelFontSize: 16,
        dataPoints: [
            
            @foreach($records as $prc)
            { y: {{$prc->price}} },
            @endforeach
        ]
    }]
});
chart.render();

}
</script>

Try this piece:试试这个:

<script>


window.onload = function () {
    var records = "<?php echo $records ?>"
    var data = records.map((function (record) {
      return {y: record.price}
    }))
    var chart = new CanvasJS.Chart("chartContainer", {
      animationEnabled: true,
      theme: "light2",
      title:{
        text: "Simple Line Chart"
      },
      data: [{
        type: "line",
        indexLabelFontSize: 16,
        dataPoints: data
      }]
    });
    chart.render();
  }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM